1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
//! All types that may be returned from [crate::Client] methods.
use crate::util::{AlertState, RuleHealth, TargetHealth};
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt;
use time::{Duration, OffsetDateTime, PrimitiveDateTime};
use url::Url;

mod de {
    use serde::{Deserialize, Deserializer};
    use std::str::FromStr;
    use time::format_description::well_known::Rfc3339;
    use time::format_description::FormatItem;
    use time::macros::format_description;
    use time::{Duration, OffsetDateTime, PrimitiveDateTime};

    const BUILD_INFO_DATE_FORMAT: &[FormatItem] = format_description!(
        "[year repr:full][month repr:numerical][day]-[hour repr:24]:[minute]:[second]"
    );

    pub(super) fn deserialize_f64<'de, D>(deserializer: D) -> Result<f64, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = String::deserialize(deserializer)?;
        let num = f64::from_str(&raw).map_err(serde::de::Error::custom)?;
        Ok(num)
    }

    pub(super) fn deserialize_rfc3339<'de, D>(deserializer: D) -> Result<OffsetDateTime, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = String::deserialize(deserializer)?;

        OffsetDateTime::parse(&raw, &Rfc3339)
            .map_err(|e| serde::de::Error::custom(format!("error parsing '{}': {}", raw, e)))
    }

    // This function is used to deserialize a specific datetime string like "20191102-16:19:59".
    pub(super) fn deserialize_build_info_date<'de, D>(
        deserializer: D,
    ) -> Result<PrimitiveDateTime, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = String::deserialize(deserializer)?;

        PrimitiveDateTime::parse(&raw, &BUILD_INFO_DATE_FORMAT)
            .map_err(|e| serde::de::Error::custom(format!("error parsing '{}': {}", raw, e)))
    }

    // This function is used to deserialize Prometheus duration strings like "1d" or "5m" or
    // composits like "1d12h10m".
    // Note that this function assumes that the input string is non-empty and that the total
    // amount of milliseconds does not exceed i64::MAX. This seems to be a reasonable assumption
    // since the Prometheus server creates durations from Go's int64 on the server side and the
    // int64 depicts the total amount of nanoseconds.
    pub(super) fn deserialize_prometheus_duration<'de, D>(
        deserializer: D,
    ) -> Result<Duration, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error as SerdeError;

        let raw_str = String::deserialize(deserializer)?;

        let mut total_milliseconds: i64 = 0;

        // Add each number character to a string until a unit character is encountered.
        // This string is then cleared to process the next number + unit.
        let mut raw_num = String::new();

        // Iterate the duration string, convert each unit to nanoseconds and add
        // it to the total.
        let mut duration_iter = raw_str.chars().peekable();

        while let Some(item) = duration_iter.next() {
            if ('0'..='9').contains(&item) {
                raw_num.push(item);
                continue;
            }

            let num = raw_num.parse::<i64>().map_err(SerdeError::custom)?;

            match item {
                'y' => {
                    total_milliseconds += num * 1000 * 60 * 60 * 24 * 365;
                }
                'w' => {
                    total_milliseconds += num * 1000 * 60 * 60 * 24 * 7;
                }
                'd' => {
                    total_milliseconds += num * 1000 * 60 * 60 * 24;
                }
                'h' => {
                    total_milliseconds += num * 1000 * 60 * 60;
                }
                'm' => {
                    if duration_iter.next_if_eq(&'s').is_some() {
                        total_milliseconds += num * 1000 * 60 * 60;
                    } else {
                        total_milliseconds += num * 1000 * 60;
                    }
                }
                's' => {
                    total_milliseconds += num * 1000;
                }
                _ => return Err(SerdeError::custom("invalid time duration")),
            };

            raw_num.clear();
        }

        Ok(Duration::milliseconds(total_milliseconds))
    }
}

#[derive(Debug, Deserialize)]
pub(crate) struct ApiResponse {
    pub(crate) status: ApiResponseStatus,
    pub(crate) data: Option<serde_json::Value>,
    #[serde(alias = "errorType")]
    pub(crate) error_type: Option<String>,
    pub(crate) error: Option<String>,
}

#[derive(Debug, Deserialize)]
pub(crate) enum ApiResponseStatus {
    #[serde(alias = "success")]
    Success,
    #[serde(alias = "error")]
    Error,
}

#[derive(Debug, Deserialize)]
pub(crate) struct QueryResult {
    #[serde(alias = "resultType")]
    pub(crate) kind: QueryResultType,
    #[serde(alias = "result")]
    pub(crate) data: serde_json::Value,
}

#[derive(Debug, Deserialize)]
pub(crate) enum QueryResultType {
    #[serde(alias = "vector")]
    Vector,
    #[serde(alias = "matrix")]
    Matrix,
    #[serde(alias = "scalar")]
    Scalar,
}

/// A wrapper for possible result types of expression queries ([crate::Client::query] and [crate::Client::query_range]).
#[derive(Clone, Debug)]
pub enum PromqlResult {
    Vector(Vec<InstantVector>),
    Matrix(Vec<RangeVector>),
    Scalar(Sample),
}

impl PromqlResult {
    /// If the result type of the query is `vector`, returns an array of [InstantVector]s. Returns `None` otherwise.
    pub fn as_instant(&self) -> Option<&[InstantVector]> {
        match self {
            PromqlResult::Vector(v) => Some(v.as_ref()),
            _ => None,
        }
    }

    /// If the result type of the query is `matrix` returns an array of [RangeVector]s. Returns `None` otherwise.
    pub fn as_range(&self) -> Option<&[RangeVector]> {
        match self {
            PromqlResult::Matrix(v) => Some(v.as_ref()),
            _ => None,
        }
    }

    /// If the result type of the query is `scalar`, returns a single [Sample]. Returns `None` otherwise.
    pub fn as_scalar(&self) -> Option<&Sample> {
        match self {
            PromqlResult::Scalar(v) => Some(v),
            _ => None,
        }
    }
}

/// A single time series containing a single data point/sample.
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct InstantVector {
    pub(crate) metric: HashMap<String, String>,
    #[serde(alias = "value")]
    pub(crate) sample: Sample,
}

impl InstantVector {
    /// Returns a reference to the set of labels (+ metric name)
    /// of this time series.
    pub fn metric(&self) -> &HashMap<String, String> {
        &self.metric
    }

    /// Returns a reference to the sample of this time series.
    pub fn sample(&self) -> &Sample {
        &self.sample
    }
}

/// A single time series containing a range of data points/samples.
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct RangeVector {
    pub(crate) metric: HashMap<String, String>,
    #[serde(alias = "values")]
    pub(crate) samples: Vec<Sample>,
}

impl RangeVector {
    /// Returns a reference to the set of labels (+ metric name)
    /// of this time series.
    pub fn metric(&self) -> &HashMap<String, String> {
        &self.metric
    }

    /// Returns a reference to the set of samples of this time series.
    pub fn samples(&self) -> &[Sample] {
        &self.samples
    }
}

/// A single data point.
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct Sample {
    pub(crate) timestamp: f64,
    #[serde(deserialize_with = "de::deserialize_f64")]
    pub(crate) value: f64,
}

impl Sample {
    /// Returns the timestamp contained in this sample.
    pub fn timestamp(&self) -> f64 {
        self.timestamp
    }

    /// Returns the value contained in this sample.
    pub fn value(&self) -> f64 {
        self.value
    }
}

/// Collection of active and dropped targets as returned by the API.
#[derive(Clone, Debug, Deserialize)]
pub struct Targets {
    #[serde(alias = "activeTargets")]
    pub(crate) active: Vec<ActiveTarget>,
    #[serde(alias = "droppedTargets")]
    pub(crate) dropped: Vec<DroppedTarget>,
}

impl Targets {
    /// Get a list of currently active targets.
    pub fn active(&self) -> &[ActiveTarget] {
        &self.active
    }

    /// Get a list of dropped targets.
    pub fn dropped(&self) -> &[DroppedTarget] {
        &self.dropped
    }
}

/// A single active target.
#[derive(Clone, Debug, Deserialize)]
pub struct ActiveTarget {
    #[serde(alias = "discoveredLabels")]
    pub(crate) discovered_labels: HashMap<String, String>,
    pub(crate) labels: HashMap<String, String>,
    #[serde(alias = "scrapePool")]
    pub(crate) scrape_pool: String,
    #[serde(alias = "scrapeUrl")]
    pub(crate) scrape_url: Url,
    #[serde(alias = "globalUrl")]
    pub(crate) global_url: Url,
    #[serde(alias = "lastError")]
    pub(crate) last_error: String,
    #[serde(alias = "lastScrape")]
    #[serde(deserialize_with = "de::deserialize_rfc3339")]
    pub(crate) last_scrape: OffsetDateTime,
    #[serde(alias = "lastScrapeDuration")]
    pub(crate) last_scrape_duration: f64,
    pub(crate) health: TargetHealth,
    #[serde(alias = "scrapeInterval")]
    #[serde(deserialize_with = "de::deserialize_prometheus_duration")]
    pub(crate) scrape_interval: Duration,
    #[serde(alias = "scrapeTimeout")]
    #[serde(deserialize_with = "de::deserialize_prometheus_duration")]
    pub(crate) scrape_timeout: Duration,
}

impl ActiveTarget {
    /// Get a set of unmodified labels as before relabelling occurred.
    pub fn discovered_labels(&self) -> &HashMap<String, String> {
        &self.discovered_labels
    }

    /// Get a set of labels after relabelling.
    pub fn labels(&self) -> &HashMap<String, String> {
        &self.labels
    }

    /// Get the scrape pool of this target.
    pub fn scrape_pool(&self) -> &str {
        &self.scrape_pool
    }

    /// Get the scrape URL of this target.
    pub fn scrape_url(&self) -> &Url {
        &self.scrape_url
    }

    /// Get the global URL of this target.
    pub fn global_url(&self) -> &Url {
        &self.global_url
    }

    /// Get the last error reported for this target.
    pub fn last_error(&self) -> &str {
        &self.last_error
    }

    /// Get the time when the last scrape occurred.
    pub fn last_scrape(&self) -> &OffsetDateTime {
        &self.last_scrape
    }

    /// Get the duration that the last scrape ran for in seconds.
    pub fn last_scrape_duration(&self) -> f64 {
        self.last_scrape_duration
    }

    /// Get the health status of this target.
    pub fn health(&self) -> TargetHealth {
        self.health
    }

    /// Get the scrape interval of this target.
    pub fn scrape_interval(&self) -> &Duration {
        &self.scrape_interval
    }

    /// Get the scrape timeout of this target.
    pub fn scrape_timeout(&self) -> &Duration {
        &self.scrape_timeout
    }
}

/// A single dropped target.
#[derive(Clone, Debug, Deserialize)]
pub struct DroppedTarget {
    #[serde(alias = "discoveredLabels")]
    pub(crate) discovered_labels: HashMap<String, String>,
}

impl DroppedTarget {
    /// Get a set of unmodified labels as before relabelling occurred.
    pub fn discovered_labels(&self) -> &HashMap<String, String> {
        &self.discovered_labels
    }
}

/// A group of rules.
#[derive(Clone, Debug, Deserialize)]
pub struct RuleGroup {
    pub(crate) rules: Vec<Rule>,
    pub(crate) file: String,
    pub(crate) interval: f64,
    pub(crate) name: String,
}

impl RuleGroup {
    /// Get a reference to all rules associated with this group.
    pub fn rules(&self) -> &[Rule] {
        &self.rules
    }

    /// Get the path to the file where this group is defined in.
    pub fn file(&self) -> &str {
        &self.file
    }

    /// Get the interval that defines how often rules are evaluated.
    pub fn interval(&self) -> f64 {
        self.interval
    }

    /// Get the name of this rule group.
    pub fn name(&self) -> &str {
        &self.name
    }
}

/// A wrapper for different types of rules that the HTTP API may return.
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "type")]
pub enum Rule {
    #[serde(alias = "recording")]
    Recording(RecordingRule),
    #[serde(alias = "alerting")]
    Alerting(AlertingRule),
}

/// An alerting rule.
#[derive(Clone, Debug, Deserialize)]
pub struct AlertingRule {
    pub(crate) alerts: Vec<Alert>,
    pub(crate) annotations: HashMap<String, String>,
    pub(crate) duration: f64,
    pub(crate) health: RuleHealth,
    pub(crate) labels: HashMap<String, String>,
    pub(crate) name: String,
    pub(crate) query: String,
}

impl AlertingRule {
    /// Get a list of active alerts fired due to this alerting rule.
    pub fn alerts(&self) -> &[Alert] {
        &self.alerts
    }

    /// Get a set of annotations set for this rule.
    pub fn annotations(&self) -> &HashMap<String, String> {
        &self.annotations
    }

    /// Get the duration that Prometheus waits for before firing for this rule.
    pub fn duration(&self) -> f64 {
        self.duration
    }

    /// Get the health state of this rule.
    pub fn health(&self) -> RuleHealth {
        self.health
    }

    /// Get a set of labels defined for this rule.
    pub fn labels(&self) -> &HashMap<String, String> {
        &self.labels
    }

    /// Get the name of this rule.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the PromQL expression that is evaluated as part of this rule.
    pub fn query(&self) -> &str {
        &self.query
    }
}

/// A recording rule.
#[derive(Clone, Debug, Deserialize)]
pub struct RecordingRule {
    pub(crate) health: RuleHealth,
    pub(crate) name: String,
    pub(crate) query: String,
    pub(crate) labels: Option<HashMap<String, String>>,
}

impl RecordingRule {
    /// Get the health state of this rule.
    pub fn health(&self) -> RuleHealth {
        self.health
    }

    /// Get the name of this rule.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the PromQL expression that is evaluated as part of this rule.
    pub fn query(&self) -> &str {
        &self.query
    }

    /// Get a set of labels defined for this rule.
    pub fn labels(&self) -> &Option<HashMap<String, String>> {
        &self.labels
    }
}

/// A single alert.
#[derive(Clone, Debug, Deserialize)]
pub struct Alert {
    #[serde(alias = "activeAt")]
    #[serde(deserialize_with = "de::deserialize_rfc3339")]
    pub(crate) active_at: OffsetDateTime,
    pub(crate) annotations: HashMap<String, String>,
    pub(crate) labels: HashMap<String, String>,
    pub(crate) state: AlertState,
    pub(crate) value: String,
}

impl Alert {
    /// Get the time when this alert started firing.
    pub fn active_at(&self) -> &OffsetDateTime {
        &self.active_at
    }

    /// Get a set of annotations associated with this alert.
    pub fn annotations(&self) -> &HashMap<String, String> {
        &self.annotations
    }

    /// Get a set of labels associated with this alert.
    pub fn labels(&self) -> &HashMap<String, String> {
        &self.labels
    }

    /// Get the state of this alert.
    pub fn state(&self) -> AlertState {
        self.state
    }

    /// Get the value as evaluated by the PromQL expression that caused the alert to fire.
    pub fn value(&self) -> &str {
        &self.value
    }
}

/// Collection of active and dropped alertmanagers as returned by the API.
#[derive(Clone, Debug, Deserialize)]
pub struct Alertmanagers {
    #[serde(alias = "activeAlertmanagers")]
    pub(crate) active: Vec<Alertmanager>,
    #[serde(alias = "droppedAlertmanagers")]
    pub(crate) dropped: Vec<Alertmanager>,
}

impl Alertmanagers {
    /// Get a list of currently active alertmanagers.
    pub fn active(&self) -> &[Alertmanager] {
        &self.active
    }

    /// Get a list of dropped alertmanagers.
    pub fn dropped(&self) -> &[Alertmanager] {
        &self.dropped
    }
}

/// A single alertmanager.
#[derive(Clone, Debug, Deserialize)]
pub struct Alertmanager {
    url: Url,
}

impl Alertmanager {
    /// Get the URL of this Alertmanager.
    pub fn url(&self) -> &Url {
        &self.url
    }
}

/// Possible metric types that the HTTP API may return.
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum MetricType {
    #[serde(alias = "counter")]
    Counter,
    #[serde(alias = "gauge")]
    Gauge,
    #[serde(alias = "histogram")]
    Histogram,
    #[serde(alias = "gaugehistogram")]
    GaugeHistogram,
    #[serde(alias = "summary")]
    Summary,
    #[serde(alias = "info")]
    Info,
    #[serde(alias = "stateset")]
    Stateset,
    #[serde(alias = "unknown")]
    Unknown,
}

impl fmt::Display for MetricType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MetricType::Counter => write!(f, "counter"),
            MetricType::Gauge => write!(f, "gauge"),
            MetricType::Histogram => write!(f, "histogram"),
            MetricType::GaugeHistogram => write!(f, "gaugehistogram"),
            MetricType::Summary => write!(f, "summary"),
            MetricType::Info => write!(f, "info"),
            MetricType::Stateset => write!(f, "stateset"),
            MetricType::Unknown => write!(f, "unknown"),
        }
    }
}

/// A target metadata object.
#[derive(Clone, Debug, Deserialize)]
pub struct TargetMetadata {
    pub(crate) target: HashMap<String, String>,
    #[serde(alias = "type")]
    pub(crate) metric_type: MetricType,
    pub(crate) metric: Option<String>,
    pub(crate) help: String,
    pub(crate) unit: String,
}

impl TargetMetadata {
    /// Get target labels.
    pub fn target(&self) -> &HashMap<String, String> {
        &self.target
    }

    /// Get the metric type.
    pub fn metric_type(&self) -> MetricType {
        self.metric_type
    }

    /// Get the metric name.
    pub fn metric(&self) -> Option<&str> {
        self.metric.as_deref()
    }

    /// Get the metric help.
    pub fn help(&self) -> &str {
        &self.help
    }

    /// Get the metric unit.
    pub fn unit(&self) -> &str {
        &self.unit
    }
}

/// A metric metadata object.
#[derive(Clone, Debug, Deserialize)]
pub struct MetricMetadata {
    #[serde(alias = "type")]
    pub(crate) metric_type: MetricType,
    pub(crate) help: String,
    pub(crate) unit: String,
}

impl MetricMetadata {
    /// Get the metric type.
    pub fn metric_type(&self) -> MetricType {
        self.metric_type
    }

    /// Get the metric help.
    pub fn help(&self) -> &str {
        &self.help
    }

    /// Get the metric unit.
    pub fn unit(&self) -> &str {
        &self.unit
    }
}

/// An object containing Prometheus server build information.
#[derive(Clone, Debug, Deserialize)]
pub struct BuildInformation {
    pub(crate) version: String,
    pub(crate) revision: String,
    pub(crate) branch: String,
    #[serde(alias = "buildUser")]
    pub(crate) build_user: String,
    #[serde(alias = "buildDate")]
    #[serde(deserialize_with = "de::deserialize_build_info_date")]
    pub(crate) build_date: PrimitiveDateTime,
    #[serde(alias = "goVersion")]
    pub(crate) go_version: String,
}

impl BuildInformation {
    /// Get the server version.
    pub fn version(&self) -> &str {
        &self.version
    }

    /// Get the git revision from which the server was built.
    pub fn revision(&self) -> &str {
        &self.revision
    }

    /// Get the git branch from which the server was built.
    pub fn branch(&self) -> &str {
        &self.branch
    }

    /// Get the user who built the server.
    pub fn build_user(&self) -> &str {
        &self.build_user
    }

    /// Get the date at which the server was built.
    pub fn build_date(&self) -> &PrimitiveDateTime {
        &self.build_date
    }

    /// Get the Go version that was used to build the server.
    pub fn go_version(&self) -> &str {
        &self.go_version
    }
}

/// An object containing Prometheus server build information.
#[derive(Clone, Debug, Deserialize)]
pub struct RuntimeInformation {
    #[serde(alias = "startTime")]
    #[serde(deserialize_with = "de::deserialize_rfc3339")]
    pub(crate) start_time: OffsetDateTime,
    #[serde(alias = "CWD")]
    pub(crate) cwd: String,
    #[serde(alias = "reloadConfigSuccess")]
    pub(crate) reload_config_success: bool,
    #[serde(alias = "lastConfigTime")]
    #[serde(deserialize_with = "de::deserialize_rfc3339")]
    pub(crate) last_config_time: OffsetDateTime,
    #[serde(alias = "corruptionCount")]
    pub(crate) corruption_count: i64,
    #[serde(alias = "goroutineCount")]
    pub(crate) goroutine_count: usize,
    #[serde(alias = "GOMAXPROCS")]
    pub(crate) go_max_procs: usize,
    #[serde(alias = "GOGC")]
    pub(crate) go_gc: String,
    #[serde(alias = "GODEBUG")]
    pub(crate) go_debug: String,
    #[serde(alias = "storageRetention")]
    #[serde(deserialize_with = "de::deserialize_prometheus_duration")]
    pub(crate) storage_retention: Duration,
}

impl RuntimeInformation {
    /// Get the server start time.
    pub fn start_time(&self) -> &OffsetDateTime {
        &self.start_time
    }

    /// Get the current working directory.
    pub fn cwd(&self) -> &str {
        &self.cwd
    }

    /// Check if the last configuration reload was successful.
    pub fn reload_config_success(&self) -> bool {
        self.reload_config_success
    }

    /// Get the time of last configuration reload.
    pub fn last_config_time(&self) -> &OffsetDateTime {
        &self.last_config_time
    }

    pub fn corruption_count(&self) -> i64 {
        self.corruption_count
    }

    pub fn goroutine_count(&self) -> usize {
        self.goroutine_count
    }

    pub fn go_max_procs(&self) -> usize {
        self.go_max_procs
    }

    pub fn go_gc(&self) -> &str {
        &self.go_gc
    }

    pub fn go_debug(&self) -> &str {
        &self.go_debug
    }

    pub fn storage_retention(&self) -> &Duration {
        &self.storage_retention
    }
}

/// Prometheus TSDB statistics.
#[derive(Clone, Debug, Deserialize)]
pub struct TsdbStatistics {
    #[serde(alias = "headStats")]
    pub(crate) head_stats: HeadStatistics,
    #[serde(alias = "seriesCountByMetricName")]
    pub(crate) series_count_by_metric_name: Vec<TsdbItemCount>,
    #[serde(alias = "labelValueCountByLabelName")]
    pub(crate) label_value_count_by_label_name: Vec<TsdbItemCount>,
    #[serde(alias = "memoryInBytesByLabelName")]
    pub(crate) memory_in_bytes_by_label_name: Vec<TsdbItemCount>,
    #[serde(alias = "seriesCountByLabelValuePair")]
    pub(crate) series_count_by_label_value_pair: Vec<TsdbItemCount>,
}

impl TsdbStatistics {
    /// Get the head block data.
    pub fn head_stats(&self) -> HeadStatistics {
        self.head_stats
    }

    /// Get a list of metric names and their series count.
    pub fn series_count_by_metric_name(&self) -> &[TsdbItemCount] {
        &self.series_count_by_metric_name
    }

    /// Get a list of label names and their value count.
    pub fn label_value_count_by_label_name(&self) -> &[TsdbItemCount] {
        &self.label_value_count_by_label_name
    }

    /// Get a list of label names and memory used in bytes.
    pub fn memory_in_bytes_by_label_name(&self) -> &[TsdbItemCount] {
        &self.memory_in_bytes_by_label_name
    }

    /// Get a list of label name/value pairs and their series count.
    pub fn series_count_by_label_value_pair(&self) -> &[TsdbItemCount] {
        &self.series_count_by_label_value_pair
    }
}

/// Prometheus TSDB head block data.
#[derive(Clone, Copy, Debug, Deserialize)]
pub struct HeadStatistics {
    #[serde(alias = "numSeries")]
    pub(crate) num_series: usize,
    #[serde(alias = "chunkCount")]
    pub(crate) chunk_count: usize,
    #[serde(alias = "minTime")]
    pub(crate) min_time: i64,
    #[serde(alias = "maxTime")]
    pub(crate) max_time: i64,
}

impl HeadStatistics {
    /// Get the number of series.
    pub fn num_series(&self) -> usize {
        self.num_series
    }

    /// Get the number of chunks.
    pub fn chunk_count(&self) -> usize {
        self.chunk_count
    }

    /// Get the current minimum timestamp in milliseconds.
    pub fn min_time(&self) -> i64 {
        self.min_time
    }

    /// Get the current maximum timestamp in milliseconds.
    pub fn max_time(&self) -> i64 {
        self.max_time
    }
}

/// Prometheus TSDB item counts used in different contexts (e.g. series count, label value count ...).
#[derive(Clone, Debug, Deserialize)]
pub struct TsdbItemCount {
    pub(crate) name: String,
    pub(crate) value: usize,
}

impl TsdbItemCount {
    /// Get the name of the item in question, e.g. metric name or label name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the count of the item in question, e.g. the series count of a given metric name.
    pub fn value(&self) -> usize {
        self.value
    }
}

/// WAL replay state.
#[derive(Clone, Copy, Debug, Deserialize)]
pub struct WalReplayStatistics {
    pub(crate) min: usize,
    pub(crate) max: usize,
    pub(crate) current: usize,
    pub(crate) state: Option<WalReplayState>,
}

impl WalReplayStatistics {
    pub fn min(&self) -> usize {
        self.min
    }

    pub fn max(&self) -> usize {
        self.max
    }

    pub fn current(&self) -> usize {
        self.current
    }

    pub fn state(&self) -> Option<WalReplayState> {
        self.state
    }
}

#[derive(Clone, Copy, Debug, Deserialize)]
pub enum WalReplayState {
    #[serde(alias = "waiting")]
    Waiting,
    #[serde(alias = "in progress")]
    InProgress,
    #[serde(alias = "done")]
    Done,
}

#[cfg(test)]
mod tests {
    // The examples used in these test cases are taken from prometheus.io.

    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_instant_vector_deserialization() {
        let data = r#"
[
  {
    "metric": {
      "__name__": "up",
      "job": "prometheus",
      "instance": "localhost:9090"
    },
    "value": [
      1435781451.781,
      "1"
    ]
  },
  {
    "metric": {
      "__name__": "up",
      "job": "node",
      "instance": "localhost:9100"
    },
    "value": [
      1435781451.781,
      "0"
    ]
  }
]
"#;
        let result: Result<Vec<InstantVector>, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_range_vector_deserialization() {
        let data = r#"
[
  {
    "metric": {
      "__name__": "up",
      "job": "prometheus",
      "instance": "localhost:9090"
    },
    "values": [
      [
        1435781430.781,
        "1"
      ],
      [
        1435781445.781,
        "1"
      ],
      [
        1435781460.781,
        "1"
      ]
    ]
  },
  {
    "metric": {
      "__name__": "up",
      "job": "node",
      "instance": "localhost:9091"
    },
    "values": [
      [
        1435781430.781,
        "0"
      ],
      [
        1435781445.781,
        "0"
      ],
      [
        1435781460.781,
        "1"
      ]
    ]
  }
]
"#;
        let result: Result<Vec<RangeVector>, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_target_deserialization() {
        let data = r#"
{
  "activeTargets": [
    {
      "discoveredLabels": {
        "__address__": "127.0.0.1:9090",
        "__metrics_path__": "/metrics",
        "__scheme__": "http",
        "job": "prometheus"
      },
      "labels": {
        "instance": "127.0.0.1:9090",
        "job": "prometheus"
      },
      "scrapePool": "prometheus",
      "scrapeUrl": "http://127.0.0.1:9090/metrics",
      "globalUrl": "http://example-prometheus:9090/metrics",
      "lastError": "",
      "lastScrape": "2017-01-17T15:07:44.723715405+01:00",
      "lastScrapeDuration": 0.050688943,
      "health": "up",
      "scrapeInterval": "1m",
      "scrapeTimeout": "10s"
    }
  ],
  "droppedTargets": [
    {
      "discoveredLabels": {
        "__address__": "127.0.0.1:9100",
        "__metrics_path__": "/metrics",
        "__scheme__": "http",
        "__scrape_interval__": "1m",
        "__scrape_timeout__": "10s",
        "job": "node"
      }
    }
  ]
}
"#;
        let result: Result<Targets, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_rule_group_deserialization() {
        let data = r#"
[
  {
    "rules": [
      {
        "alerts": [
          {
            "activeAt": "2018-07-04T20:27:12.60602144+02:00",
            "annotations": {
              "summary": "High request latency"
            },
            "labels": {
              "alertname": "HighRequestLatency",
              "severity": "page"
            },
            "state": "firing",
            "value": "1e+00"
          }
        ],
        "annotations": {
          "summary": "High request latency"
        },
        "duration": 600,
        "health": "ok",
        "labels": {
          "severity": "page"
        },
        "name": "HighRequestLatency",
        "query": "job:request_latency_seconds:mean5m{job=\"myjob\"} > 0.5",
        "type": "alerting"
      },
      {
        "health": "ok",
        "name": "job:http_inprogress_requests:sum",
        "query": "sum by (job) (http_inprogress_requests)",
        "type": "recording"
      }
    ],
    "file": "/rules.yaml",
    "interval": 60,
    "limit": 0,
    "name": "example"
  }
]
"#;
        let result: Result<Vec<RuleGroup>, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_alert_deserialization() {
        let data = r#"
[
   {
      "activeAt":"2018-07-04T20:27:12.60602144+02:00",
      "annotations":{
         
      },
      "labels":{
         "alertname":"my-alert"
      },
      "state":"firing",
      "value":"1e+00"
   }
]
"#;
        let result: Result<Vec<Alert>, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_target_metadata_deserialization_1() {
        let data = r#"
[
  {
    "target": {
      "instance": "127.0.0.1:9090",
      "job": "prometheus"
    },
    "type": "gauge",
    "help": "Number of goroutines that currently exist.",
    "unit": ""
  },
  {
    "target": {
      "instance": "127.0.0.1:9091",
      "job": "prometheus"
    },
    "type": "gauge",
    "help": "Number of goroutines that currently exist.",
    "unit": ""
  }
]
"#;
        let result: Result<Vec<TargetMetadata>, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_target_metadata_deserialization_2() {
        let data = r#"
[
  {
    "target": {
      "instance": "127.0.0.1:9090",
      "job": "prometheus"
    },
    "metric": "prometheus_treecache_zookeeper_failures_total",
    "type": "counter",
    "help": "The total number of ZooKeeper failures.",
    "unit": ""
  },
  {
    "target": {
      "instance": "127.0.0.1:9090",
      "job": "prometheus"
    },
    "metric": "prometheus_tsdb_reloads_total",
    "type": "counter",
    "help": "Number of times the database reloaded block data from disk.",
    "unit": ""
  }
]
"#;
        let result: Result<Vec<TargetMetadata>, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_metric_metadata_deserialization() {
        let data = r#"
{
  "cortex_ring_tokens": [
    {
      "type": "gauge",
      "help": "Number of tokens in the ring",
      "unit": ""
    }
  ],
  "http_requests_total": [
    {
      "type": "counter",
      "help": "Number of HTTP requests",
      "unit": ""
    },
    {
      "type": "counter",
      "help": "Amount of HTTP requests",
      "unit": ""
    }
  ]
}
"#;
        let result: Result<HashMap<String, Vec<MetricMetadata>>, serde_json::Error> =
            serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_alertmanagers_deserialization() {
        let data = r#"
{
  "activeAlertmanagers": [
    {
      "url": "http://127.0.0.1:9090/api/v1/alerts"
    }
  ],
  "droppedAlertmanagers": [
    {
      "url": "http://127.0.0.1:9093/api/v1/alerts"
    }
  ]
}
"#;
        let result: Result<Alertmanagers, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_buildinformation_deserialization() {
        let data = r#"
{
  "version": "2.13.1",
  "revision": "cb7cbad5f9a2823a622aaa668833ca04f50a0ea7",
  "branch": "master",
  "buildUser": "julius@desktop",
  "buildDate": "20191102-16:19:59",
  "goVersion": "go1.13.1"
}
"#;
        let result: Result<BuildInformation, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_runtimeinformation_deserialization() {
        let data = r#"
{
  "startTime": "2019-11-02T17:23:59.301361365+01:00",
  "CWD": "/",
  "reloadConfigSuccess": true,
  "lastConfigTime": "2019-11-02T17:23:59+01:00",
  "timeSeriesCount": 873,
  "corruptionCount": 0,
  "goroutineCount": 48,
  "GOMAXPROCS": 4,
  "GOGC": "",
  "GODEBUG": "",
  "storageRetention": "15d"
}
"#;
        let result: Result<RuntimeInformation, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_tsdb_stats_deserialization() {
        let data = r#"
{
  "headStats": {
    "numSeries": 508,
    "chunkCount": 937,
    "minTime": 1591516800000,
    "maxTime": 1598896800143
  },
  "seriesCountByMetricName": [
    {
      "name": "net_conntrack_dialer_conn_failed_total",
      "value": 20
    },
    {
      "name": "prometheus_http_request_duration_seconds_bucket",
      "value": 20
    }
  ],
  "labelValueCountByLabelName": [
    {
      "name": "__name__",
      "value": 211
    },
    {
      "name": "event",
      "value": 3
    }
  ],
  "memoryInBytesByLabelName": [
    {
      "name": "__name__",
      "value": 8266
    },
    {
      "name": "instance",
      "value": 28
    }
  ],
  "seriesCountByLabelValuePair": [
    {
      "name": "job=prometheus",
      "value": 425
    },
    {
      "name": "instance=localhost:9090",
      "value": 425
    }
  ]
}
"#;
        let result: Result<TsdbStatistics, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_wal_replay_deserialization() {
        let data = r#"
{
  "min": 2,
  "max": 5,
  "current": 40,
  "state": "waiting"
}
"#;
        let result: Result<WalReplayStatistics, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());

        let data = r#"
{
  "min": 2,
  "max": 5,
  "current": 40,
  "state": "in progress"
}
"#;
        let result: Result<WalReplayStatistics, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());

        let data = r#"
{
  "min": 2,
  "max": 5,
  "current": 40,
  "state": "done"
}
"#;
        let result: Result<WalReplayStatistics, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());

        let data = r#"
{
  "min": 2,
  "max": 5,
  "current": 40
}
"#;
        let result: Result<WalReplayStatistics, serde_json::Error> = serde_json::from_str(data);
        assert!(result.is_ok());
    }
}