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
use crate::error::{
    Error, InvalidFunctionArgument, ResponseError, UnknownResponseStatus,
    UnsupportedResponseDataType,
};
use crate::response::*;
use crate::selector::Selector;
use crate::util::{validate_duration, TargetState};
use std::collections::HashMap;

/// A helper enum that is passed to the [Client::new] function in
/// order to avoid errors on unsupported connection schemes.
pub enum Scheme {
    Http,
    Https,
}

impl Scheme {
    fn as_str(&self) -> &str {
        match self {
            Scheme::Http => "http",
            Scheme::Https => "https",
        }
    }
}

/// A client used to execute queries. It uses a [reqwest::Client] internally
/// that manages connections for us.
pub struct Client {
    pub(crate) client: reqwest::Client,
    pub(crate) base_url: String,
}

impl Default for Client {
    /// Create a Client that connects to a local Prometheus instance at port 9090.
    ///
    /// ```rust
    /// use prometheus_http_query::Client;
    ///
    /// let client: Client = Default::default();
    /// ```
    fn default() -> Self {
        Client {
            client: reqwest::Client::new(),
            base_url: String::from("http://127.0.0.1:9090/api/v1"),
        }
    }
}

impl Client {
    /// Create a Client that connects to a Prometheus instance at the
    /// given FQDN/domain and port, using either HTTP or HTTPS.
    ///
    /// Note that possible errors regarding domain name resolution or
    /// connection establishment will only be propagated from the underlying
    /// [reqwest::Client] when a query is executed.
    ///
    /// ```rust
    /// use prometheus_http_query::{Client, Scheme};
    ///
    /// let client = Client::new(Scheme::Http, "localhost", 9090);
    /// ```
    pub fn new(scheme: Scheme, host: &str, port: u16) -> Self {
        Client {
            base_url: format!("{}://{}:{}/api/v1", scheme.as_str(), host, port),
            ..Default::default()
        }
    }

    /// Perform an instant query using a [crate::RangeVector] or [crate::InstantVector].
    ///
    /// ```rust
    /// use prometheus_http_query::{Client, Scheme, InstantVector, Selector, Aggregate, Error};
    /// use prometheus_http_query::aggregations::sum;
    /// use std::convert::TryInto;
    ///
    /// fn main() -> Result<(), Error> {
    ///     let client = Client::new(Scheme::Http, "localhost", 9090);
    ///
    ///     let v: InstantVector = Selector::new()
    ///         .metric("node_cpu_seconds_total")?
    ///         .try_into()?;
    ///
    ///     let s = sum(v, Some(Aggregate::By(&["cpu"])));
    ///
    ///     let response = tokio_test::block_on( async { client.query(s, None, None).await });
    ///
    ///     assert!(response.is_ok());
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn query(
        &self,
        vector: impl std::fmt::Display,
        time: Option<i64>,
        timeout: Option<&str>,
    ) -> Result<Response, Error> {
        let mut url = self.base_url.clone();

        url.push_str("/query");

        let query = vector.to_string();
        let mut params = vec![("query", query.as_str())];

        let time = time.map(|t| t.to_string());

        if let Some(t) = &time {
            params.push(("time", t.as_str()));
        }

        if let Some(t) = timeout {
            validate_duration(t)?;
            params.push(("timeout", t));
        }

        let raw_response = self
            .client
            .get(&url)
            .query(params.as_slice())
            .send()
            .await
            .map_err(Error::Reqwest)?;

        // NOTE: Can be changed to .map(async |resp| resp.json ...)
        // when async closures are stable.
        let mapped_response = match raw_response.error_for_status() {
            Ok(res) => res
                .json::<HashMap<String, serde_json::Value>>()
                .await
                .map_err(Error::Reqwest)?,
            Err(err) => return Err(Error::Reqwest(err)),
        };

        parse_query_response(mapped_response)
    }

    pub async fn query_range(
        &self,
        vector: impl std::fmt::Display,
        start: i64,
        end: i64,
        step: &str,
        timeout: Option<&str>,
    ) -> Result<Response, Error> {
        let mut url = self.base_url.clone();

        url.push_str("/query_range");

        validate_duration(step)?;

        let query = vector.to_string();
        let start = start.to_string();
        let end = end.to_string();

        let mut params = vec![
            ("query", query.as_str()),
            ("start", start.as_str()),
            ("end", end.as_str()),
            ("step", step),
        ];

        if let Some(t) = timeout {
            validate_duration(t)?;
            params.push(("timeout", t));
        }

        let raw_response = self
            .client
            .get(&url)
            .query(params.as_slice())
            .send()
            .await
            .map_err(Error::Reqwest)?;

        // NOTE: Can be changed to .map(async |resp| resp.json ...)
        // when async closures are stable.
        let mapped_response = match raw_response.error_for_status() {
            Ok(res) => res
                .json::<HashMap<String, serde_json::Value>>()
                .await
                .map_err(Error::Reqwest)?,
            Err(err) => return Err(Error::Reqwest(err)),
        };

        parse_query_response(mapped_response)
    }

    /// Find time series by series selectors.
    ///
    /// ```rust
    /// use prometheus_http_query::{Client, Scheme, Selector, Error};
    ///
    /// fn main() -> Result<(), Error> {
    ///     let client = Client::new(Scheme::Http, "localhost", 9090);
    ///
    ///     let s1 = Selector::new()
    ///         .with("handler", "/api/v1/query");
    ///
    ///     let s2 = Selector::new()
    ///         .with("job", "node")
    ///         .regex_match("mode", ".+");
    ///
    ///     let set = vec![s1, s2];
    ///
    ///     let response = tokio_test::block_on( async { client.series(&set, None, None).await });
    ///
    ///     assert!(response.is_ok());
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn series(
        &self,
        selectors: &[Selector<'_>],
        start: Option<i64>,
        end: Option<i64>,
    ) -> Result<Response, Error> {
        let mut url = self.base_url.clone();

        url.push_str("/series");

        let mut params = vec![];

        let start = start.map(|t| t.to_string());

        if let Some(s) = &start {
            params.push(("start", s.as_str()));
        }

        let end = end.map(|t| t.to_string());

        if let Some(e) = &end {
            params.push(("end", e.as_str()));
        }

        if selectors.is_empty() {
            return Err(Error::InvalidFunctionArgument(InvalidFunctionArgument {
                message: String::from("at least one match[] argument (Selector) must be provided in order to query the series endpoint")
            }));
        }

        let selectors: Vec<String> = selectors
            .iter()
            .map(|s| match s.to_string().as_str().split_once('}') {
                Some(split) => {
                    let mut s = split.0.to_owned();
                    s.push('}');
                    s
                }
                None => s.to_string(),
            })
            .collect();

        for selector in &selectors {
            params.push(("match[]", &selector));
        }

        let raw_response = self
            .client
            .get(&url)
            .query(params.as_slice())
            .send()
            .await
            .map_err(Error::Reqwest)?;

        // NOTE: Can be changed to .map(async |resp| resp.json ...)
        // when async closures are stable.
        let mapped_response = match raw_response.error_for_status() {
            Ok(res) => res
                .json::<HashMap<String, serde_json::Value>>()
                .await
                .map_err(Error::Reqwest)?,
            Err(err) => return Err(Error::Reqwest(err)),
        };

        parse_series_response(mapped_response)
    }

    /// Retrieve all label names (or use [Selector]s to select time series to read label names from).
    ///
    /// ```rust
    /// use prometheus_http_query::{Client, Scheme, Selector, Error};
    ///
    /// fn main() -> Result<(), Error> {
    ///     let client = Client::new(Scheme::Http, "localhost", 9090);
    ///
    ///     // To retrieve a list of all labels:
    ///     let response = tokio_test::block_on( async { client.labels(None, None, None).await });
    ///
    ///     assert!(response.is_ok());
    ///
    ///     // To retrieve a list of labels that appear in specific time series, use Selectors:
    ///     let s1 = Selector::new()
    ///         .with("handler", "/api/v1/query");
    ///
    ///     let s2 = Selector::new()
    ///         .with("job", "node")
    ///         .regex_match("mode", ".+");
    ///
    ///     let set = Some(vec![s1, s2]);
    ///
    ///     let response = tokio_test::block_on( async { client.labels(set, None, None).await });
    ///
    ///     assert!(response.is_ok());
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn labels(
        &self,
        selectors: Option<Vec<Selector<'_>>>,
        start: Option<i64>,
        end: Option<i64>,
    ) -> Result<Response, Error> {
        let mut url = self.base_url.clone();

        url.push_str("/labels");

        let mut params = vec![];

        let start = start.map(|t| t.to_string());

        if let Some(s) = &start {
            params.push(("start", s.as_str()));
        }

        let end = end.map(|t| t.to_string());

        if let Some(e) = &end {
            params.push(("end", e.as_str()));
        }

        let selectors: Option<Vec<String>> = selectors.map(|vec| {
            vec.iter()
                .map(|s| match s.to_string().as_str().split_once('}') {
                    Some(split) => {
                        let mut s = split.0.to_owned();
                        s.push('}');
                        s
                    }
                    None => s.to_string(),
                })
                .collect()
        });

        if let Some(ref selector_vec) = selectors {
            for selector in selector_vec {
                params.push(("match[]", &selector));
            }
        }

        let raw_response = self
            .client
            .get(&url)
            .query(params.as_slice())
            .send()
            .await
            .map_err(Error::Reqwest)?;

        // NOTE: Can be changed to .map(async |resp| resp.json ...)
        // when async closures are stable.
        let mapped_response = match raw_response.error_for_status() {
            Ok(res) => res
                .json::<HashMap<String, serde_json::Value>>()
                .await
                .map_err(Error::Reqwest)?,
            Err(err) => return Err(Error::Reqwest(err)),
        };

        parse_label_name_response(mapped_response)
    }

    /// Retrieve all label values for a label name (or use [Selector]s to select the time series to read label values from)
    ///
    /// ```rust
    /// use prometheus_http_query::{Client, Scheme, Selector, Error};
    ///
    /// fn main() -> Result<(), Error> {
    ///     let client = Client::new(Scheme::Http, "localhost", 9090);
    ///
    ///     // To retrieve a list of all label values for a specific label name:
    ///     let response = tokio_test::block_on( async { client.label_values("job", None, None, None).await });
    ///
    ///     assert!(response.is_ok());
    ///
    ///     // To retrieve a list of label values of labels in specific time series instead:
    ///     let s1 = Selector::new()
    ///         .regex_match("instance", ".+");
    ///
    ///     let set = Some(vec![s1]);
    ///
    ///     let response = tokio_test::block_on( async { client.label_values("job", set, None, None).await });
    ///
    ///     assert!(response.is_ok());
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn label_values(
        &self,
        label: &str,
        selectors: Option<Vec<Selector<'_>>>,
        start: Option<i64>,
        end: Option<i64>,
    ) -> Result<Response, Error> {
        let mut url = self.base_url.clone();

        url.push_str("/label/");
        url.push_str(label);
        url.push_str("/values");

        let mut params = vec![];

        let start = start.map(|t| t.to_string());

        if let Some(s) = &start {
            params.push(("start", s.as_str()));
        }

        let end = end.map(|t| t.to_string());

        if let Some(e) = &end {
            params.push(("end", e.as_str()));
        }

        let selectors: Option<Vec<String>> = selectors.map(|vec| {
            vec.iter()
                .map(|s| match s.to_string().as_str().split_once('}') {
                    Some(split) => {
                        let mut s = split.0.to_owned();
                        s.push('}');
                        s
                    }
                    None => s.to_string(),
                })
                .collect()
        });

        if let Some(ref selector_vec) = selectors {
            for selector in selector_vec {
                params.push(("match[]", &selector));
            }
        }

        let raw_response = self
            .client
            .get(&url)
            .query(params.as_slice())
            .send()
            .await
            .map_err(Error::Reqwest)?;

        // NOTE: Can be changed to .map(async |resp| resp.json ...)
        // when async closures are stable.
        let mapped_response = match raw_response.error_for_status() {
            Ok(res) => res
                .json::<HashMap<String, serde_json::Value>>()
                .await
                .map_err(Error::Reqwest)?,
            Err(err) => return Err(Error::Reqwest(err)),
        };

        parse_label_value_response(mapped_response)
    }

    /// Query the current state of target discovery.
    ///
    /// ```rust
    /// use prometheus_http_query::{Client, Scheme, Error, TargetState};
    /// use std::convert::TryInto;
    ///
    /// fn main() -> Result<(), Error> {
    ///     let client = Client::new(Scheme::Http, "localhost", 9090);
    ///
    ///     let response = tokio_test::block_on( async { client.targets(None).await });
    ///
    ///     assert!(response.is_ok());
    ///
    ///     // Filter targets by type:
    ///     let response = tokio_test::block_on( async { client.targets(Some(TargetState::Active)).await });
    ///
    ///     assert!(response.is_ok());
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn targets(&self, state: Option<TargetState>) -> Result<Response, Error> {
        let mut url = self.base_url.clone();

        url.push_str("/targets");

        let mut params = vec![];

        let state = state.map(|s| s.to_string());

        if let Some(s) = &state {
            params.push(("state", s.as_str()))
        }

        let raw_response = self
            .client
            .get(&url)
            .query(params.as_slice())
            .send()
            .await
            .map_err(Error::Reqwest)?;

        // NOTE: Can be changed to .map(async |resp| resp.json ...)
        // when async closures are stable.
        let mapped_response = match raw_response.error_for_status() {
            Ok(res) => res
                .json::<HashMap<String, serde_json::Value>>()
                .await
                .map_err(Error::Reqwest)?,
            Err(err) => return Err(Error::Reqwest(err)),
        };

        parse_target_response(mapped_response)
    }
}

// Parses the API response from a loosely typed Hashmap to a Response that
// encapsulates a vector of Hashmaps that hold label names and values.
// "Value"s are rigorously "unwrapped" in the process as each of these
// is expected to be part of the JSON response.
fn parse_series_response(response: HashMap<String, serde_json::Value>) -> Result<Response, Error> {
    let status = response["status"].as_str().unwrap();

    match status {
        "success" => {
            let data = response["data"].as_array().unwrap();

            let mut result = vec![];

            for datum in data {
                let metric: HashMap<String, String> =
                    serde_json::from_value(datum.to_owned()).unwrap();
                result.push(metric);
            }

            Ok(Response::Series(result))
        }
        "error" => {
            return Err(Error::ResponseError(ResponseError {
                kind: response["errorType"].as_str().unwrap().to_string(),
                message: response["error"].as_str().unwrap().to_string(),
            }))
        }
        _ => {
            return Err(Error::UnknownResponseStatus(UnknownResponseStatus(
                status.to_string(),
            )))
        }
    }
}

// Parses the API response from a loosely typed Hashmap to a Response that
// holds information about active and dropped targets.
// "Value"s are rigorously "unwrapped" in the process as each of these
// is expected to be part of the JSON response.
fn parse_target_response(response: HashMap<String, serde_json::Value>) -> Result<Response, Error> {
    let status = response["status"].as_str().unwrap();

    match status {
        "success" => {
            let raw_targets = response["data"].to_owned();
            let targets: Targets = serde_json::from_value(raw_targets).unwrap();
            Ok(Response::Targets(targets))
        }
        "error" => {
            return Err(Error::ResponseError(ResponseError {
                kind: response["errorType"].as_str().unwrap().to_string(),
                message: response["error"].as_str().unwrap().to_string(),
            }))
        }
        _ => {
            return Err(Error::UnknownResponseStatus(UnknownResponseStatus(
                status.to_string(),
            )))
        }
    }
}

// Parses the API response from a loosely typed Hashmap to a Response that
// encapsulates a vector of label names.
// "Value"s are rigorously "unwrapped" in the process as each of these
// is expected to be part of the JSON response.
fn parse_label_name_response(
    response: HashMap<String, serde_json::Value>,
) -> Result<Response, Error> {
    let status = response["status"].as_str().unwrap();

    match status {
        "success" => {
            let data = response["data"].as_array().unwrap();

            let mut result = vec![];

            for datum in data {
                result.push(datum.as_str().unwrap().to_owned());
            }

            Ok(Response::LabelNames(result))
        }
        "error" => {
            return Err(Error::ResponseError(ResponseError {
                kind: response["errorType"].as_str().unwrap().to_string(),
                message: response["error"].as_str().unwrap().to_string(),
            }))
        }
        _ => {
            return Err(Error::UnknownResponseStatus(UnknownResponseStatus(
                status.to_string(),
            )))
        }
    }
}

// Parses the API response from a loosely typed Hashmap to a Response that
// encapsulates a vector of label values.
// "Value"s are rigorously "unwrapped" in the process as each of these
// is expected to be part of the JSON response.
fn parse_label_value_response(
    response: HashMap<String, serde_json::Value>,
) -> Result<Response, Error> {
    let status = response["status"].as_str().unwrap();

    match status {
        "success" => {
            let data = response["data"].as_array().unwrap();

            let mut result = vec![];

            for datum in data {
                result.push(datum.as_str().unwrap().to_owned());
            }

            Ok(Response::LabelValues(result))
        }
        "error" => {
            return Err(Error::ResponseError(ResponseError {
                kind: response["errorType"].as_str().unwrap().to_string(),
                message: response["error"].as_str().unwrap().to_string(),
            }))
        }
        _ => {
            return Err(Error::UnknownResponseStatus(UnknownResponseStatus(
                status.to_string(),
            )))
        }
    }
}

// Parses the API response from a loosely typed Hashmap to a Response that
// encapsulates a vector of samples of type "vector" or "matrix"
// "Value"s are rigorously "unwrapped" in the process as each of these
// is expected to be part of the JSON response.
fn parse_query_response(response: HashMap<String, serde_json::Value>) -> Result<Response, Error> {
    let status = response["status"].as_str().unwrap();

    match status {
        "success" => {
            let data_obj = response["data"].as_object().unwrap();
            let data_type = data_obj["resultType"].as_str().unwrap();
            let data = data_obj["result"].as_array().unwrap().to_owned();

            match data_type {
                "vector" => {
                    let mut result: Vec<Vector> = vec![];

                    for datum in data {
                        let vector: Vector = serde_json::from_value(datum).unwrap();
                        result.push(vector);
                    }

                    Ok(Response::Vector(result))
                }
                "matrix" => {
                    let mut result: Vec<Matrix> = vec![];

                    for datum in data {
                        let matrix: Matrix = serde_json::from_value(datum).unwrap();
                        result.push(matrix);
                    }

                    Ok(Response::Matrix(result))
                }
                _ => {
                    return Err(Error::UnsupportedResponseDataType(
                        UnsupportedResponseDataType(data_type.to_string()),
                    ))
                }
            }
        }
        "error" => {
            return Err(Error::ResponseError(ResponseError {
                kind: response["errorType"].as_str().unwrap().to_string(),
                message: response["error"].as_str().unwrap().to_string(),
            }))
        }
        _ => {
            return Err(Error::UnknownResponseStatus(UnknownResponseStatus(
                status.to_string(),
            )))
        }
    }
}