Skip to main content

prometheus_http_query/
client.rs

1use crate::error::{ClientError, Error};
2use crate::response::*;
3use crate::util::{self, build_final_url, Duration, RuleKind, TargetState, ToBaseUrl};
4use reqwest::header::{HeaderMap, HeaderValue, IntoHeaderName, CONTENT_TYPE};
5use reqwest::Method as HttpMethod;
6use serde::{de::DeserializeOwned, Serialize};
7use std::collections::HashMap;
8use url::Url;
9
10/// Provides a builder to set some query parameters in the context
11/// of an instant query before sending it to Prometheus.
12#[derive(Clone, Debug)]
13pub struct InstantQueryBuilder {
14    client: Client,
15    params: Vec<(&'static str, String)>,
16    headers: Option<HeaderMap<HeaderValue>>,
17}
18
19/// See the official documentation for a thorough explanation on the filters that can
20/// be set: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries).
21impl InstantQueryBuilder {
22    /// Set the evaluation timestamp (Unix timestamp in seconds, e.g. 1659182624).
23    /// If this is not set the evaluation timestamp will default to the current Prometheus
24    /// server time.
25    pub fn time(mut self, time: i64) -> Self {
26        self.params.push(("time", time.to_string()));
27        self
28    }
29
30    /// Set the evaluation timeout. Must be positive.
31    /// If this is not set the timeout will default to the value of the "-query.timeout" flag of the Prometheus server.
32    pub fn timeout(mut self, timeout: Duration) -> Self {
33        self.params.push(("timeout", timeout.to_string()));
34        self
35    }
36
37    /// Set maximum number of returned series. 0 means disabled.
38    pub fn limit(mut self, limit: i64) -> Self {
39        self.params.push(("limit", limit.to_string()));
40        self
41    }
42
43    /// Override the lookback period just for this query.
44    pub fn lookback_delta(mut self, duration: Duration) -> Self {
45        self.params.push(("lookback_delta", duration.to_string()));
46        self
47    }
48
49    /// Instruct Prometheus to compile query statistics as part of the API response.
50    pub fn stats(mut self) -> Self {
51        self.params.push(("stats", String::from("all")));
52        self
53    }
54
55    /// Include an additional header to the request.
56    pub fn header<K: IntoHeaderName, T: Into<HeaderValue>>(mut self, name: K, value: T) -> Self {
57        self.headers
58            .get_or_insert_with(Default::default)
59            .append(name, value.into());
60        self
61    }
62
63    /// Include an additional parameter to the request.
64    pub fn query(mut self, name: &'static str, value: impl ToString) -> Self {
65        self.params.push((name, value.to_string()));
66        self
67    }
68
69    /// Execute the instant query (using HTTP GET) and return the parsed API response.
70    pub async fn get(self) -> Result<PromqlResult, Error> {
71        let response = self.get_raw().await?;
72        Client::deserialize(response).await
73    }
74
75    /// Execute the instant query (using HTTP POST) and return the parsed API response.
76    /// Using a POST request is useful in the context of larger PromQL queries when
77    /// the size of the final URL may break Prometheus' or an intermediate proxies' URL
78    /// character limits.
79    pub async fn post(self) -> Result<PromqlResult, Error> {
80        let response = self.post_raw().await?;
81        Client::deserialize(response).await
82    }
83
84    /// Execute the instant query (using HTTP GET) and return the raw API response.
85    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
86        self.client
87            .send("api/v1/query", &self.params, HttpMethod::GET, self.headers)
88            .await
89    }
90
91    /// Execute the instant query (using HTTP POST) and return the raw API response.
92    /// Using a POST request is useful in the context of larger PromQL queries when
93    /// the size of the final URL may break Prometheus' or an intermediate proxies' URL
94    /// character limits.
95    pub async fn post_raw(self) -> Result<reqwest::Response, Error> {
96        self.client
97            .send("api/v1/query", &self.params, HttpMethod::POST, self.headers)
98            .await
99    }
100}
101
102/// Provides a builder to set some query parameters in the context
103/// of a range query before sending it to Prometheus.
104#[derive(Clone, Debug)]
105pub struct RangeQueryBuilder {
106    client: Client,
107    params: Vec<(&'static str, String)>,
108    headers: Option<HeaderMap<HeaderValue>>,
109}
110
111/// See the official documentation for a thorough explanation on the filters that can
112/// be set: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries).
113impl RangeQueryBuilder {
114    /// Set the evaluation timeout. Must be positive.
115    /// If this is not set the timeout will default to the value of the "-query.timeout" flag of the Prometheus server.
116    pub fn timeout(mut self, timeout: Duration) -> Self {
117        self.params.push(("timeout", timeout.to_string()));
118        self
119    }
120
121    /// Set maximum number of returned series. 0 means disabled.
122    pub fn limit(mut self, limit: i64) -> Self {
123        self.params.push(("limit", limit.to_string()));
124        self
125    }
126
127    /// Override the lookback period just for this query.
128    pub fn lookback_delta(mut self, duration: Duration) -> Self {
129        self.params.push(("lookback_delta", duration.to_string()));
130        self
131    }
132
133    /// Instruct Prometheus to compile query statistics as part of the API response.
134    pub fn stats(mut self) -> Self {
135        self.params.push(("stats", String::from("all")));
136        self
137    }
138
139    /// Include an additional header to the request.
140    pub fn header<K: IntoHeaderName, T: Into<HeaderValue>>(mut self, name: K, value: T) -> Self {
141        self.headers
142            .get_or_insert_with(Default::default)
143            .append(name, value.into());
144        self
145    }
146
147    /// Include an additional parameter to the request.
148    pub fn query(mut self, name: &'static str, value: impl ToString) -> Self {
149        self.params.push((name, value.to_string()));
150        self
151    }
152
153    /// Execute the range query (using HTTP GET) and return the parsed API response.
154    pub async fn get(self) -> Result<PromqlResult, Error> {
155        let response = self.get_raw().await?;
156        Client::deserialize(response).await
157    }
158
159    /// Execute the instant query (using HTTP POST) and return the parsed API response.
160    /// Using a POST request is useful in the context of larger PromQL queries when
161    /// the size of the final URL may break Prometheus' or an intermediate proxies' URL
162    /// character limits.
163    pub async fn post(self) -> Result<PromqlResult, Error> {
164        let response = self.post_raw().await?;
165        Client::deserialize(response).await
166    }
167
168    /// Execute the range query (using HTTP GET) and return the raw API response.
169    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
170        self.client
171            .send(
172                "api/v1/query_range",
173                &self.params,
174                HttpMethod::GET,
175                self.headers,
176            )
177            .await
178    }
179
180    /// Execute the instant query (using HTTP POST) and return the raw API response.
181    /// Using a POST request is useful in the context of larger PromQL queries when
182    /// the size of the final URL may break Prometheus' or an intermediate proxies' URL
183    /// character limits.
184    pub async fn post_raw(self) -> Result<reqwest::Response, Error> {
185        self.client
186            .send(
187                "api/v1/query_range",
188                &self.params,
189                HttpMethod::POST,
190                self.headers,
191            )
192            .await
193    }
194}
195
196/// Provides methods to build a query to the rules endpoint and send it to Prometheus.
197#[derive(Clone, Debug)]
198pub struct RulesQueryBuilder {
199    client: Client,
200    kind: Option<RuleKind>,
201    rule_names: Vec<String>,
202    rule_groups: Vec<String>,
203    files: Vec<String>,
204    exclude_alerts: Option<bool>,
205    selectors: Vec<String>,
206}
207
208/// Note that Prometheus combines all filters that have been set in the final request
209/// and only returns rules that match all filters.<br>
210/// See the official documentation for a thorough explanation on the filters that can
211/// be set: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#rules).
212impl RulesQueryBuilder {
213    /// Set this to instruct Prometheus to only return a specific type of rule
214    /// (either recording or alerting rules) instead of both. Calling this repeatedly
215    /// will replace the current setting.
216    pub fn kind(mut self, kind: RuleKind) -> Self {
217        self.kind = Some(kind);
218        self
219    }
220
221    /// Pass rule names to instruct Prometheus to only return those rules whose
222    /// names match one of them. This method can be called repeatedly and merge
223    /// the names with those that have been set before.
224    pub fn rule_names<T>(mut self, names: T) -> Self
225    where
226        T: IntoIterator,
227        T::Item: std::fmt::Display,
228    {
229        self.rule_names
230            .extend(names.into_iter().map(|n| n.to_string()));
231        self
232    }
233
234    /// Pass a rule name to instruct Prometheus to return rules that match this name.
235    /// This method can be called repeatedly to extend the set of rule names that
236    /// will be sent to Prometheus.
237    pub fn rule_name(mut self, name: impl std::fmt::Display) -> Self {
238        self.rule_names.push(name.to_string());
239        self
240    }
241
242    /// Pass group names to instruct Prometheus to only return those rules that are
243    /// part of one of these groups. This method can be called repeatedly and merge
244    /// the group names with those that have been set before.
245    pub fn rule_groups<T>(mut self, groups: T) -> Self
246    where
247        T: IntoIterator,
248        T::Item: std::fmt::Display,
249    {
250        self.rule_groups
251            .extend(groups.into_iter().map(|g| g.to_string()));
252        self
253    }
254
255    /// Pass a group name to instruct Prometheus to return rules that are part of this
256    /// group. This method can be called repeatedly to extend the set of group names
257    /// that will be sent to Prometheus.
258    pub fn rule_group(mut self, group: impl std::fmt::Display) -> Self {
259        self.rule_groups.push(group.to_string());
260        self
261    }
262
263    /// Pass file names to instruct Prometheus to only return those rules that are
264    /// defined in one of those files. This method can be called repeatedly and merge
265    /// the file names with those that have been set before.
266    pub fn files<T>(mut self, files: T) -> Self
267    where
268        T: IntoIterator,
269        T::Item: std::fmt::Display,
270    {
271        self.files.extend(files.into_iter().map(|f| f.to_string()));
272        self
273    }
274
275    /// Pass a file name to instruct Prometheus to return rules that are defined in
276    /// this file. This method can be called repeatedly to extend the set of file names
277    /// that will be sent to Prometheus.
278    pub fn file(mut self, file: impl std::fmt::Display) -> Self {
279        self.files.push(file.to_string());
280        self
281    }
282
283    /// Set this to instruct Prometheus to only return rules, but not active alerts.
284    /// Calling this repeatedly will replace the current setting.
285    pub fn exclude_alerts(mut self, exclude_alerts: bool) -> Self {
286        self.exclude_alerts = Some(exclude_alerts);
287        self
288    }
289
290    /// Only return rules that have configured labels that satisfy the label selectors.
291    /// This be used multiple times to extend the set of label selectors, in which case
292    /// rules that match any of the sets of label selectors are returned.<br>
293    /// This corresponds to setting the `match[]` query parameter repeatedly.
294    pub fn match_many<T>(mut self, selectors: T) -> Self
295    where
296        T: IntoIterator,
297        T::Item: std::fmt::Display,
298    {
299        self.selectors
300            .extend(selectors.into_iter().map(|item| item.to_string()));
301        self
302    }
303
304    /// Only return rules that have configured labels that satisfy the label selectors.
305    /// This be used multiple times to extend the set of label selectors, in which case
306    /// rules that match any of the sets of label selectors are returned.<br>
307    /// This corresponds to setting the `match[]` query parameter once.
308    pub fn match_one(mut self, selector: impl std::fmt::Display) -> Self {
309        self.selectors.push(selector.to_string());
310        self
311    }
312
313    /// Execute the rules query (using HTTP GET) and return the [`RuleGroup`]s sent
314    /// by Prometheus.
315    pub async fn get(self) -> Result<Vec<RuleGroup>, Error> {
316        let response = self.get_raw().await?;
317        Client::deserialize(response)
318            .await
319            .map(|r: RuleGroups| r.groups)
320    }
321
322    /// Execute the rules query (using HTTP GET) and return the raw response sent
323    /// by Prometheus.
324    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
325        let mut params = vec![];
326
327        if let Some(k) = self.kind {
328            params.push(("type", k.to_query_param()))
329        }
330
331        for name in self.rule_names {
332            params.push(("rule_name[]", name))
333        }
334
335        for group in self.rule_groups {
336            params.push(("rule_group[]", group))
337        }
338
339        for file in self.files {
340            params.push(("file[]", file))
341        }
342
343        if let Some(exclude_alerts) = self.exclude_alerts {
344            params.push(("exclude_alerts", exclude_alerts.to_string()));
345        }
346
347        for selector in self.selectors {
348            params.push(("match[]", selector.to_string()));
349        }
350
351        self.client
352            .send("api/v1/rules", &params, HttpMethod::GET, None)
353            .await
354    }
355}
356
357/// Provides methods to build a query to the target metadata endpoint and send it to Prometheus.
358#[derive(Clone, Debug)]
359pub struct TargetMetadataQueryBuilder {
360    client: Client,
361    match_target: Option<String>,
362    metric: Option<String>,
363    limit: Option<i64>,
364}
365
366/// Note that Prometheus combines all filters that have been set in the final request
367/// and only returns target metadata that matches all filters.<br>
368/// See the official documentation for a thorough explanation on the filters that can
369/// be set: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-target-metadata).
370impl TargetMetadataQueryBuilder {
371    /// Pass a label selector to instruct Prometheus to filter targets by their label
372    /// sets.
373    /// Calling this repeatedly will replace the current label selector.
374    pub fn match_target(mut self, match_target: impl std::fmt::Display) -> Self {
375        self.match_target = Some(match_target.to_string());
376        self
377    }
378
379    /// Set this to only retrieve target metadata for this metric.
380    /// Calling this repeatedly will replace the current metric name.
381    pub fn metric(mut self, metric: impl std::fmt::Display) -> Self {
382        self.metric = Some(metric.to_string());
383        self
384    }
385
386    /// Limit the maximum number of targets to match.
387    /// Calling this repeatedly will replace the current limit.
388    pub fn limit(mut self, limit: i64) -> Self {
389        self.limit = Some(limit);
390        self
391    }
392
393    /// Execute the target metadata query (using HTTP GET) and return the collection of
394    /// [`TargetMetadata`] sent by Prometheus.
395    pub async fn get(self) -> Result<Vec<TargetMetadata>, Error> {
396        let response = self.get_raw().await?;
397        Client::deserialize(response).await
398    }
399
400    /// Execute the target metadata query (using HTTP GET) and return the raw response
401    /// sent by Prometheus.
402    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
403        let mut params = vec![];
404
405        if let Some(metric) = self.metric {
406            params.push(("metric", metric))
407        }
408
409        if let Some(match_target) = self.match_target {
410            params.push(("match_target", match_target))
411        }
412
413        if let Some(limit) = self.limit {
414            params.push(("limit", limit.to_string()))
415        }
416
417        self.client
418            .send("api/v1/targets/metadata", &params, HttpMethod::GET, None)
419            .await
420    }
421}
422
423/// Provides methods to build a query to the targets endpoint and send it to Prometheus.
424#[derive(Clone, Debug)]
425pub struct TargetsQueryBuilder {
426    client: Client,
427    state: Option<TargetState>,
428    scrape_pool: Option<String>,
429}
430
431/// Note that Prometheus combines all filters that have been set in the final request
432/// and only returns targets that match all filters.<br>
433/// See the official documentation for a thorough explanation on the filters that can
434/// be set: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#targets).
435impl TargetsQueryBuilder {
436    /// Set this to filter by active or dropped targets.
437    /// Calling this repeatedly will replace the current filter.
438    pub fn state(mut self, state: TargetState) -> Self {
439        self.state = Some(state);
440        self
441    }
442
443    /// Set this to filter by scrape pool name.
444    /// Calling this repeatedly will replace the current filter.
445    pub fn scrape_pool(mut self, name: impl std::fmt::Display) -> Self {
446        self.scrape_pool = Some(name.to_string());
447        self
448    }
449
450    /// Execute the targets query (using HTTP GET) and return the [`Targets`]
451    /// sent by Prometheus.
452    pub async fn get(self) -> Result<Targets, Error> {
453        let response = self.get_raw().await?;
454        Client::deserialize(response).await
455    }
456
457    /// Execute the targets query (using HTTP GET) and return the raw response
458    /// sent by Prometheus.
459    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
460        let mut params = vec![];
461
462        if let Some(state) = self.state {
463            params.push(("state", state.to_string()))
464        }
465
466        if let Some(scrape_pool) = self.scrape_pool {
467            params.push(("scrapePool", scrape_pool))
468        }
469
470        self.client
471            .send("api/v1/targets", &params, HttpMethod::GET, None)
472            .await
473    }
474}
475
476/// Provides methods to build a query to the metric metadata endpoint and send it to Prometheus.
477#[derive(Clone, Debug)]
478pub struct MetricMetadataQueryBuilder {
479    client: Client,
480    metric: Option<String>,
481    limit: Option<i64>,
482    limit_per_metric: Option<i64>,
483}
484
485/// Note that Prometheus combines all filters that have been set in the final request
486/// and only returns metric metadata that matches all filters.<br>
487/// See the official documentation for a thorough explanation on the filters that can
488/// be set: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-metric-metadata).
489impl MetricMetadataQueryBuilder {
490    /// Instruct Prometheus to filter metadata by this metric name.
491    /// Calling this repeatedly will replace the current setting.
492    pub fn metric(mut self, metric: impl std::fmt::Display) -> Self {
493        self.metric = Some(metric.to_string());
494        self
495    }
496
497    /// Limit the maximum number of metrics to return.
498    /// Calling this repeatedly will replace the current limit.
499    pub fn limit(mut self, limit: i64) -> Self {
500        self.limit = Some(limit);
501        self
502    }
503
504    /// Limit the maximum number of metadata to return per metric.
505    /// Calling this repeatedly will replace the current limit.
506    pub fn limit_per_metric(mut self, limit_per_metric: i64) -> Self {
507        self.limit_per_metric = Some(limit_per_metric);
508        self
509    }
510
511    /// Execute the metric metadata query (using HTTP GET) and return the collection of
512    /// [`MetricMetadata`] sent by Prometheus.
513    pub async fn get(self) -> Result<HashMap<String, Vec<MetricMetadata>>, Error> {
514        let response = self.get_raw().await?;
515        Client::deserialize(response).await
516    }
517
518    /// Execute the metric metadata query (using HTTP GET) and return the raw response
519    /// sent by Prometheus.
520    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
521        let mut params = vec![];
522
523        if let Some(metric) = self.metric {
524            params.push(("metric", metric.to_string()))
525        }
526
527        if let Some(limit) = self.limit {
528            params.push(("limit", limit.to_string()))
529        }
530
531        if let Some(limit_per_metric) = self.limit_per_metric {
532            params.push(("limit_per_metric", limit_per_metric.to_string()))
533        }
534
535        self.client
536            .send("api/v1/metadata", &params, HttpMethod::GET, None)
537            .await
538    }
539}
540
541/// Provides methods to build a query to the series endpoint and send it to Prometheus.
542#[derive(Clone, Debug)]
543pub struct SeriesQueryBuilder {
544    client: Client,
545    selectors: Vec<String>,
546    start: Option<i64>,
547    end: Option<i64>,
548    limit: Option<i64>,
549}
550
551/// Note that Prometheus combines all filters that have been set in the final request
552/// and only returns series that matches all filters.<br>
553/// See the official documentation for a thorough explanation on the filters that can
554/// be set: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#finding-series-by-label-matchers).
555impl SeriesQueryBuilder {
556    /// Add series selectors that tell Prometheus which series to return. This can
557    /// be used multiple times to extend the set of series selectors.
558    /// At least one selector must be provided.<br>
559    /// This corresponds to setting the `match[]` query parameter repeatedly.
560    pub fn match_many<T>(mut self, selectors: T) -> Self
561    where
562        T: IntoIterator,
563        T::Item: std::fmt::Display,
564    {
565        self.selectors
566            .extend(selectors.into_iter().map(|item| item.to_string()));
567        self
568    }
569
570    /// Add a series selector that tells Prometheus which series to return. This can
571    /// be used multiple times to extend the set of series selectors.
572    /// At least one selector must be provided.<br>
573    /// This corresponds to setting the `match[]` query parameter once.
574    pub fn match_one(mut self, selector: impl std::fmt::Display) -> Self {
575        self.selectors.push(selector.to_string());
576        self
577    }
578
579    /// Limit the amount of metadata returned by setting a start time
580    /// (UNIX timestamp in seconds).
581    /// Calling this repeatedly will replace the current setting.<br>
582    pub fn start(mut self, start: i64) -> Self {
583        self.start = Some(start);
584        self
585    }
586
587    /// Limit the amount of metadata returned by setting an end time
588    /// (UNIX timestamp in seconds).
589    /// Calling this repeatedly will replace the current setting.<br>
590    pub fn end(mut self, end: i64) -> Self {
591        self.end = Some(end);
592        self
593    }
594
595    /// Set maximum number of returned series. 0 means disabled.
596    pub fn limit(mut self, limit: i64) -> Self {
597        self.limit = Some(limit);
598        self
599    }
600
601    /// Execute the series metadata query (using HTTP GET) and return a collection of
602    /// matching time series sent by Prometheus.
603    pub async fn get(self) -> Result<Vec<HashMap<String, String>>, Error> {
604        let response = self.get_raw().await?;
605        Client::deserialize(response).await
606    }
607
608    /// Execute the series metadata query (using HTTP GET) and return the raw response
609    /// sent by Prometheus.
610    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
611        let mut params = vec![];
612
613        for selector in self.selectors {
614            params.push(("match[]", selector.to_string()));
615        }
616
617        if let Some(start) = self.start {
618            params.push(("start", start.to_string()));
619        }
620
621        if let Some(end) = self.end {
622            params.push(("end", end.to_string()));
623        }
624
625        if let Some(limit) = self.limit {
626            params.push(("limit", limit.to_string()));
627        }
628
629        self.client
630            .send("api/v1/series", &params, HttpMethod::GET, None)
631            .await
632    }
633}
634
635/// Provides methods to build a query to retrieve label names from Prometheus.
636#[derive(Clone, Debug)]
637pub struct LabelNamesQueryBuilder {
638    client: Client,
639    selectors: Vec<String>,
640    start: Option<i64>,
641    end: Option<i64>,
642    limit: Option<i64>,
643}
644
645impl LabelNamesQueryBuilder {
646    /// Add series selectors to filter the time series from which Prometheus
647    /// reads label names.<br>
648    /// This can be called multiple times to merge the series selectors with
649    /// those that have been set before.<br>
650    /// This corresponds to setting `match[]` from [`Getting label names`](https://prometheus.io/docs/prometheus/latest/querying/api/#getting-label-names) repeatedly.
651    pub fn match_many<T>(mut self, selectors: T) -> Self
652    where
653        T: IntoIterator,
654        T::Item: std::fmt::Display,
655    {
656        self.selectors
657            .extend(selectors.into_iter().map(|item| item.to_string()));
658        self
659    }
660
661    /// Add a series selector to filter the time series from which Prometheus
662    /// reads label names.<br>
663    /// This can be called multiple times to merge the series selectors with
664    /// those that have been set before.<br>
665    /// This corresponds to setting `match[]` from [`Getting label names`](https://prometheus.io/docs/prometheus/latest/querying/api/#getting-label-names) once.
666    pub fn match_one(mut self, selector: impl std::fmt::Display) -> Self {
667        self.selectors.push(selector.to_string());
668        self
669    }
670
671    /// Limit the amount of metadata returned by setting a start time
672    /// (UNIX timestamp in seconds).
673    /// Calling this repeatedly will replace the current setting.
674    pub fn start(mut self, start: i64) -> Self {
675        self.start = Some(start);
676        self
677    }
678
679    /// Limit the amount of metadata returned by setting an end time
680    /// (UNIX timestamp in seconds).
681    /// Calling this repeatedly will replace the current setting.
682    pub fn end(mut self, end: i64) -> Self {
683        self.end = Some(end);
684        self
685    }
686
687    /// Limit the maximum number of returned series.
688    /// Calling this repeatedly will replace the current limit.
689    pub fn limit(mut self, limit: i64) -> Self {
690        self.limit = Some(limit);
691        self
692    }
693
694    /// Execute the query (using HTTP GET) and retrieve a collection of
695    /// label names.
696    pub async fn get(self) -> Result<Vec<String>, Error> {
697        let response = self.get_raw().await?;
698        Client::deserialize(response).await
699    }
700
701    /// Execute the query (using HTTP GET) and retrieve the raw response.
702    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
703        let mut params = vec![];
704
705        for selector in self.selectors {
706            params.push(("match[]", selector.to_string()));
707        }
708
709        if let Some(start) = self.start {
710            params.push(("start", start.to_string()));
711        }
712
713        if let Some(end) = self.end {
714            params.push(("end", end.to_string()));
715        }
716
717        if let Some(limit) = self.limit {
718            params.push(("limit", limit.to_string()));
719        }
720
721        self.client
722            .send("api/v1/labels", &params, HttpMethod::GET, None)
723            .await
724    }
725}
726
727/// Provides methods to build a query to retrieve label values for a specific
728/// label from Prometheus.
729#[derive(Clone, Debug)]
730pub struct LabelValuesQueryBuilder {
731    client: Client,
732    label: String,
733    selectors: Vec<String>,
734    start: Option<i64>,
735    end: Option<i64>,
736    limit: Option<i64>,
737}
738
739impl LabelValuesQueryBuilder {
740    /// Add series selectors to filter the time series from which Prometheus
741    /// reads label values.<br>
742    /// This can be called multiple times to merge the series selectors with
743    /// those that have been set before.<br>
744    /// This corresponds to setting `match[]` from [`Querying label values`](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-label-values) repeatedly.
745    pub fn match_many<T>(mut self, selectors: T) -> Self
746    where
747        T: IntoIterator,
748        T::Item: std::fmt::Display,
749    {
750        self.selectors
751            .extend(selectors.into_iter().map(|item| item.to_string()));
752        self
753    }
754
755    /// Add a series selector to filter the time series from which Prometheus
756    /// reads label values.<br>
757    /// This can be called multiple times to merge the series selectors with
758    /// those that have been set before.<br>
759    /// This corresponds to setting `match[]` from [`Querying label values`](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-label-values) once.
760    pub fn match_one(mut self, selector: impl std::fmt::Display) -> Self {
761        self.selectors.push(selector.to_string());
762        self
763    }
764
765    /// Limit the amount of metadata returned by setting a start time
766    /// (UNIX timestamp in seconds).
767    /// Calling this repeatedly will replace the current setting.
768    pub fn start(mut self, start: i64) -> Self {
769        self.start = Some(start);
770        self
771    }
772
773    /// Limit the amount of metadata returned by setting an end time
774    /// (UNIX timestamp in seconds).
775    /// Calling this repeatedly will replace the current setting.
776    pub fn end(mut self, end: i64) -> Self {
777        self.end = Some(end);
778        self
779    }
780
781    /// Limit the maximum number of returned series.
782    /// Calling this repeatedly will replace the current limit.
783    pub fn limit(mut self, limit: i64) -> Self {
784        self.limit = Some(limit);
785        self
786    }
787
788    /// Execute the query (using HTTP GET) and retrieve a collection of
789    /// label values for the given label name.
790    pub async fn get(self) -> Result<Vec<String>, Error> {
791        let response = self.get_raw().await?;
792        Client::deserialize(response).await
793    }
794
795    /// Execute the query (using HTTP GET) and retrieve a collection of
796    /// label values for the given label name.
797    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
798        let mut params = vec![];
799
800        for selector in self.selectors {
801            params.push(("match[]", selector.to_string()));
802        }
803
804        if let Some(start) = self.start {
805            params.push(("start", start.to_string()));
806        }
807
808        if let Some(end) = self.end {
809            params.push(("end", end.to_string()));
810        }
811
812        if let Some(limit) = self.limit {
813            params.push(("limit", limit.to_string()));
814        }
815
816        let path = format!("api/v1/label/{}/values", self.label);
817
818        self.client
819            .send(&path, &params, HttpMethod::GET, None)
820            .await
821    }
822}
823
824/// Provides a builder to choose how the response from Prometheus
825/// is returned to the caller.
826#[derive(Clone, Debug)]
827pub struct AlertsQueryBuilder {
828    client: Client,
829}
830
831impl AlertsQueryBuilder {
832    /// Execute the query (using HTTP GET) and retrieve a collection of
833    /// active alerts.
834    pub async fn get(self) -> Result<Vec<Alert>, Error> {
835        let response = self.get_raw().await?;
836        Client::deserialize(response)
837            .await
838            .map(|r: Alerts| r.alerts)
839    }
840
841    /// Execute the query (using HTTP GET) and retrieve the raw response
842    /// from the [`reqwest`] crate.
843    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
844        self.client
845            .send("api/v1/alerts", &(), HttpMethod::GET, None)
846            .await
847    }
848}
849
850/// Provides a builder to choose how the response from Prometheus
851/// is returned to the caller.
852#[derive(Clone, Debug)]
853pub struct AlertmanagersQueryBuilder {
854    client: Client,
855}
856
857impl AlertmanagersQueryBuilder {
858    /// Execute the query (using HTTP GET) and retrieve an overview
859    /// of the current state of Prometheus alertmanager discovery.
860    pub async fn get(self) -> Result<Alertmanagers, Error> {
861        let response = self.get_raw().await?;
862        Client::deserialize(response).await
863    }
864
865    /// Execute the query (using HTTP GET) and retrieve the raw response
866    /// from the [`reqwest`] crate.
867    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
868        self.client
869            .send("api/v1/alertmanagers", &(), HttpMethod::GET, None)
870            .await
871    }
872}
873
874/// Provides a builder to choose how the response from Prometheus
875/// is returned to the caller.
876#[derive(Clone, Debug)]
877pub struct FlagsQueryBuilder {
878    client: Client,
879}
880
881impl FlagsQueryBuilder {
882    /// Execute the query (using HTTP GET) and retrieve flag values
883    /// that Prometheus was configured with.
884    pub async fn get(self) -> Result<HashMap<String, String>, Error> {
885        let response = self.get_raw().await?;
886        Client::deserialize(response).await
887    }
888
889    /// Execute the query (using HTTP GET) and retrieve the raw response
890    /// from the [`reqwest`] crate.
891    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
892        self.client
893            .send("api/v1/status/flags", &(), HttpMethod::GET, None)
894            .await
895    }
896}
897
898/// Provides a builder to choose how the response from Prometheus
899/// is returned to the caller.
900#[derive(Clone, Debug)]
901pub struct BuildInformationQueryBuilder {
902    client: Client,
903}
904
905impl BuildInformationQueryBuilder {
906    /// Execute the query (using HTTP GET) and retrieve various build information
907    /// properties about the Prometheus server.
908    pub async fn get(self) -> Result<BuildInformation, Error> {
909        let response = self.get_raw().await?;
910        Client::deserialize(response).await
911    }
912
913    /// Execute the query (using HTTP GET) and retrieve the raw response
914    /// from the [`reqwest`] crate.
915    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
916        self.client
917            .send("api/v1/status/buildinfo", &(), HttpMethod::GET, None)
918            .await
919    }
920}
921
922/// Provides a builder to choose how the response from Prometheus
923/// is returned to the caller.
924#[derive(Clone, Debug)]
925pub struct RuntimeInformationQueryBuilder {
926    client: Client,
927}
928
929impl RuntimeInformationQueryBuilder {
930    /// Execute the query (using HTTP GET) and retrieve runtime information
931    /// properties about the Prometheus server.
932    pub async fn get(self) -> Result<RuntimeInformation, Error> {
933        let response = self.get_raw().await?;
934        Client::deserialize(response).await
935    }
936
937    /// Execute the query (using HTTP GET) and retrieve the raw response
938    /// from the [`reqwest`] crate.
939    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
940        self.client
941            .send("api/v1/status/runtimeinfo", &(), HttpMethod::GET, None)
942            .await
943    }
944}
945
946/// Provides a builder to choose how the response from Prometheus
947/// is returned to the caller.
948#[derive(Clone, Debug)]
949pub struct TsdbStatisticsQueryBuilder {
950    client: Client,
951}
952
953impl TsdbStatisticsQueryBuilder {
954    /// Execute the query (using HTTP GET) and retrieve various cardinality
955    /// statistics the Prometheus TSDB.
956    pub async fn get(self) -> Result<TsdbStatistics, Error> {
957        let response = self.get_raw().await?;
958        Client::deserialize(response).await
959    }
960
961    /// Execute the query (using HTTP GET) and retrieve the raw response
962    /// from the [`reqwest`] crate.
963    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
964        self.client
965            .send("api/v1/status/tsdb", &(), HttpMethod::GET, None)
966            .await
967    }
968}
969
970/// Provides a builder to choose how the response from Prometheus
971/// is returned to the caller.
972#[derive(Clone, Debug)]
973pub struct WalReplayStatisticsQueryBuilder {
974    client: Client,
975}
976
977impl WalReplayStatisticsQueryBuilder {
978    /// Execute the query (using HTTP GET) and retrieve information about
979    /// the WAL replay.
980    pub async fn get(self) -> Result<WalReplayStatistics, Error> {
981        let response = self.get_raw().await?;
982        Client::deserialize(response).await
983    }
984
985    /// Execute the query (using HTTP GET) and retrieve the raw response
986    /// from the [`reqwest`] crate.
987    pub async fn get_raw(self) -> Result<reqwest::Response, Error> {
988        self.client
989            .send("api/v1/status/walreplay", &(), HttpMethod::GET, None)
990            .await
991    }
992}
993
994/// A client used to execute queries. It uses a [`reqwest::Client`] internally
995/// that manages connections for us.
996#[derive(Clone, Debug)]
997pub struct Client {
998    pub(crate) client: reqwest::Client,
999    pub(crate) base_url: Url,
1000}
1001
1002impl Default for Client {
1003    /// Create a standard Client that sends requests to "http://127.0.0.1:9090/".
1004    ///
1005    /// ```rust
1006    /// use prometheus_http_query::Client;
1007    ///
1008    /// let client = Client::default();
1009    /// ```
1010    fn default() -> Self {
1011        Client {
1012            client: reqwest::Client::new(),
1013            base_url: Url::parse("http://127.0.0.1:9090/").unwrap(),
1014        }
1015    }
1016}
1017
1018impl std::str::FromStr for Client {
1019    type Err = crate::error::Error;
1020
1021    /// Create a Client from a custom base URL. Note that the API-specific
1022    /// path segments (like `/api/v1/query`) are added automatically.
1023    ///
1024    /// ```rust
1025    /// use prometheus_http_query::Client;
1026    /// use std::str::FromStr;
1027    ///
1028    /// let client = Client::from_str("http://proxy.example.com/prometheus");
1029    /// assert!(client.is_ok());
1030    /// ```
1031    fn from_str(url: &str) -> Result<Self, Self::Err> {
1032        let client = Client {
1033            base_url: url.to_base_url()?,
1034            client: reqwest::Client::new(),
1035        };
1036        Ok(client)
1037    }
1038}
1039
1040impl std::convert::TryFrom<&str> for Client {
1041    type Error = crate::error::Error;
1042
1043    /// Create a [`Client`] from a custom base URL. Note that the API-specific
1044    /// path segments (like `/api/v1/query`) are added automatically.
1045    ///
1046    /// ```rust
1047    /// use prometheus_http_query::Client;
1048    /// use std::convert::TryFrom;
1049    ///
1050    /// let client = Client::try_from("http://proxy.example.com/prometheus");
1051    /// assert!(client.is_ok());
1052    /// ```
1053    fn try_from(url: &str) -> Result<Self, Self::Error> {
1054        let client = Client {
1055            base_url: url.to_base_url()?,
1056            client: reqwest::Client::new(),
1057        };
1058        Ok(client)
1059    }
1060}
1061
1062impl std::convert::TryFrom<String> for Client {
1063    type Error = crate::error::Error;
1064
1065    /// Create a [`Client`] from a custom base URL. Note that the API-specific
1066    /// path segments (like `/api/v1/query`) are added automatically.
1067    ///
1068    /// ```rust
1069    /// use prometheus_http_query::Client;
1070    /// use std::convert::TryFrom;
1071    ///
1072    /// let url = String::from("http://proxy.example.com/prometheus");
1073    /// let client = Client::try_from(url);
1074    /// assert!(client.is_ok());
1075    /// ```
1076    fn try_from(url: String) -> Result<Self, Self::Error> {
1077        let client = Client {
1078            base_url: url.to_base_url()?,
1079            client: reqwest::Client::new(),
1080        };
1081        Ok(client)
1082    }
1083}
1084
1085impl Client {
1086    /// Return a reference to the wrapped [`reqwest::Client`], i.e. to
1087    /// use it for other requests unrelated to the Prometheus API.
1088    ///
1089    /// ```rust
1090    /// use prometheus_http_query::{Client};
1091    ///
1092    /// #[tokio::main(flavor = "current_thread")]
1093    /// async fn main() -> Result<(), anyhow::Error> {
1094    ///     let client = Client::default();
1095    ///
1096    ///     // An amittedly bad example, but that is not the point.
1097    ///     let response = client
1098    ///         .inner()
1099    ///         .head("http://127.0.0.1:9090")
1100    ///         .send()
1101    ///         .await?;
1102    ///
1103    ///     // Prometheus does not allow HEAD requests.
1104    ///     assert_eq!(response.status(), reqwest::StatusCode::METHOD_NOT_ALLOWED);
1105    ///     Ok(())
1106    /// }
1107    /// ```
1108    pub fn inner(&self) -> &reqwest::Client {
1109        &self.client
1110    }
1111
1112    /// Return a reference to the base URL that is used in requests to
1113    /// the Prometheus API.
1114    ///
1115    /// ```rust
1116    /// use prometheus_http_query::Client;
1117    /// use std::str::FromStr;
1118    ///
1119    /// let client = Client::default();
1120    ///
1121    /// assert_eq!(client.base_url().as_str(), "http://127.0.0.1:9090/");
1122    ///
1123    /// let client = Client::from_str("https://proxy.example.com:8443/prometheus").unwrap();
1124    ///
1125    /// assert_eq!(client.base_url().as_str(), "https://proxy.example.com:8443/prometheus");
1126    /// ```
1127    pub fn base_url(&self) -> &Url {
1128        &self.base_url
1129    }
1130
1131    /// Create a Client from a custom [`reqwest::Client`] and URL.
1132    /// This way you can account for all extra parameters (e.g. x509 authentication)
1133    /// that may be needed to connect to Prometheus or an intermediate proxy,
1134    /// by building it into the [`reqwest::Client`].
1135    ///
1136    /// ```rust
1137    /// use prometheus_http_query::Client;
1138    ///
1139    /// fn main() -> Result<(), anyhow::Error> {
1140    ///     let client = {
1141    ///         let c = reqwest::Client::builder()
1142    ///             .no_proxy()
1143    ///             .build()?;
1144    ///         Client::from(c, "https://prometheus.example.com")
1145    ///     };
1146    ///
1147    ///     assert!(client.is_ok());
1148    ///     Ok(())
1149    /// }
1150    /// ```
1151    pub fn from(client: reqwest::Client, url: &str) -> Result<Self, Error> {
1152        let base_url = url.to_base_url()?;
1153        Ok(Client { base_url, client })
1154    }
1155
1156    /// Build and send the final HTTP request. Parse the result as JSON if the
1157    /// `Content-Type` header indicates that the payload is JSON. Otherwise it is
1158    /// assumed that an intermediate proxy sends a plain text error.
1159    async fn send<S: Serialize>(
1160        &self,
1161        path: &str,
1162        params: &S,
1163        method: HttpMethod,
1164        headers: Option<HeaderMap<HeaderValue>>,
1165    ) -> Result<reqwest::Response, Error> {
1166        let url = build_final_url(self.base_url.clone(), path);
1167
1168        let mut request = match method {
1169            HttpMethod::GET => self.client.get(url).query(params),
1170            HttpMethod::POST => self.client.post(url).form(params),
1171            _ => unreachable!(),
1172        };
1173
1174        if let Some(headers) = headers {
1175            request = request.headers(headers);
1176        }
1177
1178        let response = request.send().await.map_err(|source| {
1179            Error::Client(ClientError {
1180                message: "failed to send request to server",
1181                source: Some(source),
1182            })
1183        })?;
1184        Ok(response)
1185    }
1186
1187    /// Create an [`InstantQueryBuilder`] from a PromQL query allowing you to set some query parameters
1188    /// (e.g. evaluation timeout) before finally sending the instant query to the server.
1189    ///
1190    /// # Arguments
1191    /// * `query` - PromQL query to exeute
1192    ///
1193    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries)
1194    ///
1195    /// ```rust
1196    /// use prometheus_http_query::{Client, Duration};
1197    /// use std::str::FromStr;
1198    ///
1199    /// #[tokio::main(flavor = "current_thread")]
1200    /// async fn main() -> Result<(), anyhow::Error> {
1201    ///     let client = Client::default();
1202    ///
1203    ///     let response = client.query("prometheus_http_request_total")
1204    ///         .time(time::macros::datetime!(1970-01-01 0:00 -1).unix_timestamp())
1205    ///         .timeout(Duration::from_str("10s")?.into())
1206    ///         .get()
1207    ///         .await?;
1208    ///
1209    ///     assert!(response.data().as_vector().is_some());
1210    ///
1211    ///     // Or send a POST request without extra parameters. Also set
1212    ///     // the lookback period to one hour.
1213    ///     let response = client.query("prometheus_http_request_total")
1214    ///         .lookback_delta(3600.into())
1215    ///         .post()
1216    ///         .await?;
1217    ///
1218    ///     assert!(response.data().as_vector().is_some());
1219    ///
1220    ///     Ok(())
1221    /// }
1222    /// ```
1223    pub fn query(&self, query: impl std::fmt::Display) -> InstantQueryBuilder {
1224        InstantQueryBuilder {
1225            client: self.clone(),
1226            params: vec![("query", query.to_string())],
1227            headers: Default::default(),
1228        }
1229    }
1230
1231    /// Create a [`RangeQueryBuilder`] from a PromQL query allowing you to set some query parameters
1232    /// (e.g. evaluation timeout) before finally sending the range query to the server.
1233    ///
1234    /// # Arguments
1235    /// * `query` - PromQL query to exeute
1236    /// * `start` - Start timestamp as Unix timestamp (seconds)
1237    /// * `end` - End timestamp as Unix timestamp (seconds)
1238    /// * `step` - Query resolution step width as float number of seconds
1239    ///
1240    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries)
1241    ///
1242    /// ```rust
1243    /// use prometheus_http_query::{Client, Duration};
1244    /// use std::str::FromStr;
1245    ///
1246    /// #[tokio::main(flavor = "current_thread")]
1247    /// async fn main() -> Result<(), anyhow::Error> {
1248    ///     let client = Client::default();
1249    ///
1250    ///     let q = "prometheus_http_requests_total";
1251    ///
1252    ///     let response = client.query_range(q, 1648373100, 1648373300, 10.0)
1253    ///         .timeout(10.into())
1254    ///         .get()
1255    ///         .await?;
1256    ///
1257    ///     assert!(response.data().as_matrix().is_some());
1258    ///
1259    ///     // Or make a POST request.
1260    ///     // A Prometheus time duration can also be parsed from a string when
1261    ///     // it is not available in its float representation.
1262    ///     let duration = Duration::from_str("10s")?;
1263    ///     let response = client.query_range(q, 1648373100, 1648373300, duration.into())
1264    ///         .limit(10)
1265    ///         .lookback_delta((6.5).into())
1266    ///         .post()
1267    ///         .await?;
1268    ///
1269    ///     assert!(response.data().as_matrix().is_some());
1270    ///
1271    ///     Ok(())
1272    /// }
1273    /// ```
1274    pub fn query_range(
1275        &self,
1276        query: impl std::fmt::Display,
1277        start: i64,
1278        end: i64,
1279        step: f64,
1280    ) -> RangeQueryBuilder {
1281        RangeQueryBuilder {
1282            client: self.clone(),
1283            params: vec![
1284                ("query", query.to_string()),
1285                ("start", start.to_string()),
1286                ("end", end.to_string()),
1287                ("step", step.to_string()),
1288            ],
1289            headers: Default::default(),
1290        }
1291    }
1292
1293    /// Create a [`SeriesQueryBuilder`] to apply filters to a series metadata
1294    /// query before sending it to Prometheus.<br>
1295    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#finding-series-by-label-matchers)
1296    ///
1297    /// ```rust
1298    /// use prometheus_http_query::{Client, Selector};
1299    ///
1300    /// #[tokio::main(flavor = "current_thread")]
1301    /// async fn main() -> Result<(), anyhow::Error> {
1302    ///     let client = Client::default();
1303    ///
1304    ///     // Use free-form series selectors to only return time series
1305    ///     // matching a certain label set.
1306    ///     {
1307    ///         let response = client.series()
1308    ///             .match_one("up")
1309    ///             .match_one("{job=\"node\",instance=~\".+\"}")
1310    ///             .limit(5)
1311    ///             .get()
1312    ///             .await;
1313    ///
1314    ///         assert!(response.is_ok());
1315    ///     }
1316    ///
1317    ///     // Use strongly typed series selectors to only return time series
1318    ///     // matching a certain label set.
1319    ///     {
1320    ///         let s1 = Selector::new()
1321    ///             .eq("handler", "/api/v1/query");
1322    ///
1323    ///         let s2 = Selector::new()
1324    ///             .eq("job", "node")
1325    ///             .regex_eq("mode", ".+");
1326    ///
1327    ///         let response = client.series()
1328    ///             .match_many(&[s1, s2])
1329    ///             .get()
1330    ///             .await;
1331    ///
1332    ///         assert!(response.is_ok());
1333    ///     }
1334    ///
1335    ///     Ok(())
1336    /// }
1337    /// ```
1338    pub fn series(&self) -> SeriesQueryBuilder {
1339        SeriesQueryBuilder {
1340            client: self.clone(),
1341            selectors: vec![],
1342            start: None,
1343            end: None,
1344            limit: None,
1345        }
1346    }
1347
1348    /// Create a [`LabelNamesQueryBuilder`] to apply filters to a query for the label
1349    /// names endpoint before sending it to Prometheus.
1350    ///
1351    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#getting-label-names)
1352    ///
1353    /// ```rust
1354    /// use prometheus_http_query::{Client, Selector};
1355    ///
1356    /// #[tokio::main(flavor = "current_thread")]
1357    /// async fn main() -> Result<(), anyhow::Error> {
1358    ///     let client = Client::default();
1359    ///
1360    ///     // To retrieve a list of all labels:
1361    ///     let response = client.label_names().get().await;
1362    ///
1363    ///     assert!(response.is_ok());
1364    ///
1365    ///     // Use free-form selectors to retrieve a list of labels
1366    ///     // that appear in specific time series:
1367    ///     {
1368    ///         let response = client.label_names()
1369    ///             .match_one("{handler=\"/api/v1/query\"}")
1370    ///             .match_one("{job=\"node\",mode=~\".+\"}")
1371    ///             .get()
1372    ///             .await;
1373    ///
1374    ///         assert!(response.is_ok());
1375    ///     }
1376    ///
1377    ///     // Use strongly typed selectors to retrieve a list of labels
1378    ///     // that appear in specific time series:
1379    ///     {
1380    ///         let s1 = Selector::new()
1381    ///             .eq("handler", "/api/v1/query");
1382    ///
1383    ///         let s2 = Selector::new()
1384    ///             .eq("job", "node")
1385    ///             .regex_eq("mode", ".+");
1386    ///
1387    ///         let response = client.label_names().match_many(&[s1, s2]).get().await;
1388    ///
1389    ///         assert!(response.is_ok());
1390    ///     }
1391    ///
1392    ///     Ok(())
1393    /// }
1394    /// ```
1395    pub fn label_names(&self) -> LabelNamesQueryBuilder {
1396        LabelNamesQueryBuilder {
1397            client: self.clone(),
1398            selectors: vec![],
1399            start: None,
1400            end: None,
1401            limit: None,
1402        }
1403    }
1404
1405    /// Create a [`LabelValuesQueryBuilder`] to apply filters to a query for the label
1406    /// values endpoint before sending it to Prometheus.
1407    ///
1408    /// # Arguments
1409    /// * `label` - Name of the label to return all occuring label values for.
1410    ///
1411    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-label-values)
1412    ///
1413    /// ```rust
1414    /// use prometheus_http_query::{Client, Selector};
1415    ///
1416    /// #[tokio::main(flavor = "current_thread")]
1417    /// async fn main() -> Result<(), anyhow::Error> {
1418    ///     let client = Client::default();
1419    ///
1420    ///     // To retrieve a list of all label values for a specific label name:
1421    ///     let response = client.label_values("job").get().await;
1422    ///
1423    ///     assert!(response.is_ok());
1424    ///
1425    ///     // Using free-form series selectors to retrieve a list of label values
1426    ///     // that appear in specific time series:
1427    ///     {
1428    ///         let response = client.label_values("job")
1429    ///             .match_one("{instance=~\".+\"}")
1430    ///             .get()
1431    ///             .await;
1432    ///
1433    ///         assert!(response.is_ok());
1434    ///     }
1435    ///
1436    ///     // Using strongly typed series selectors to retrieve a list of label
1437    ///     // values that appear in specific time series:
1438    ///     {
1439    ///         let selector = Selector::new()
1440    ///             .regex_eq("instance", ".+");
1441    ///
1442    ///         let response = client.label_values("job")
1443    ///             .match_one(&selector)
1444    ///             .get()
1445    ///             .await;
1446    ///
1447    ///         assert!(response.is_ok());
1448    ///     }
1449    ///
1450    ///     Ok(())
1451    /// }
1452    /// ```
1453    pub fn label_values(&self, label: impl std::fmt::Display) -> LabelValuesQueryBuilder {
1454        LabelValuesQueryBuilder {
1455            client: self.clone(),
1456            label: label.to_string(),
1457            selectors: vec![],
1458            start: None,
1459            end: None,
1460            limit: None,
1461        }
1462    }
1463
1464    /// Query the current state of target discovery.
1465    ///
1466    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#targets)
1467    ///
1468    /// ```rust
1469    /// use prometheus_http_query::{Client, TargetState};
1470    ///
1471    /// #[tokio::main(flavor = "current_thread")]
1472    /// async fn main() -> Result<(), anyhow::Error> {
1473    ///     let client = Client::default();
1474    ///
1475    ///     let response = client.targets().get().await;
1476    ///
1477    ///     assert!(response.is_ok());
1478    ///
1479    ///     // Filter targets by state and scrape pool name.
1480    ///     let response = client.targets()
1481    ///         .state(TargetState::Active)
1482    ///         .scrape_pool("node_exporter")
1483    ///         .get().await;
1484    ///
1485    ///     assert!(response.is_ok());
1486    ///
1487    ///     Ok(())
1488    /// }
1489    /// ```
1490    pub fn targets(&self) -> TargetsQueryBuilder {
1491        TargetsQueryBuilder {
1492            client: self.clone(),
1493            state: None,
1494            scrape_pool: None,
1495        }
1496    }
1497
1498    /// Create a [`RulesQueryBuilder`] to apply filters to the rules query before
1499    /// sending it to Prometheus.
1500    ///
1501    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#rules)
1502    ///
1503    /// ```rust
1504    /// use prometheus_http_query::{Client, RuleKind};
1505    ///
1506    /// #[tokio::main(flavor = "current_thread")]
1507    /// async fn main() -> Result<(), anyhow::Error> {
1508    ///     let client = Client::default();
1509    ///
1510    ///     let response = client.rules().get().await;
1511    ///
1512    ///     assert!(response.is_ok());
1513    ///
1514    ///     // Filter rules by type:
1515    ///     let response = client.rules().kind(RuleKind::Alerting).get().await;
1516    ///
1517    ///     assert!(response.is_ok());
1518    ///
1519    ///     Ok(())
1520    /// }
1521    /// ```
1522    pub fn rules(&self) -> RulesQueryBuilder {
1523        RulesQueryBuilder {
1524            client: self.clone(),
1525            kind: None,
1526            rule_names: vec![],
1527            rule_groups: vec![],
1528            files: vec![],
1529            exclude_alerts: None,
1530            selectors: vec![],
1531        }
1532    }
1533
1534    /// Retrieve a list of active alerts.
1535    ///
1536    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#alerts)
1537    ///
1538    /// ```rust
1539    /// use prometheus_http_query::Client;
1540    ///
1541    /// #[tokio::main(flavor = "current_thread")]
1542    /// async fn main() -> Result<(), anyhow::Error> {
1543    ///     let client = Client::default();
1544    ///
1545    ///     let response = client.alerts().get().await;
1546    ///
1547    ///     assert!(response.is_ok());
1548    ///
1549    ///     Ok(())
1550    /// }
1551    /// ```
1552    pub fn alerts(&self) -> AlertsQueryBuilder {
1553        AlertsQueryBuilder {
1554            client: self.clone(),
1555        }
1556        /*
1557        let response = self
1558            .send("api/v1/alerts", &(), HttpMethod::GET, None)
1559            .await?;
1560        Client::deserialize(response)
1561            .await
1562        .map(|r: Alerts| r.alerts)
1563        */
1564    }
1565
1566    /// Retrieve a list of flags that Prometheus was configured with.
1567    ///
1568    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#flags)
1569    ///
1570    /// ```rust
1571    /// use prometheus_http_query::Client;
1572    ///
1573    /// #[tokio::main(flavor = "current_thread")]
1574    /// async fn main() -> Result<(), anyhow::Error> {
1575    ///     let client = Client::default();
1576    ///
1577    ///     let response = client.flags().get().await;
1578    ///
1579    ///     assert!(response.is_ok());
1580    ///
1581    ///     Ok(())
1582    /// }
1583    /// ```
1584    pub fn flags(&self) -> FlagsQueryBuilder {
1585        FlagsQueryBuilder {
1586            client: self.clone(),
1587        }
1588    }
1589
1590    /// Retrieve Prometheus server build information.
1591    ///
1592    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#build-information)
1593    ///
1594    /// ```rust
1595    /// use prometheus_http_query::Client;
1596    ///
1597    /// #[tokio::main(flavor = "current_thread")]
1598    /// async fn main() -> Result<(), anyhow::Error> {
1599    ///     let client = Client::default();
1600    ///
1601    ///     let response = client.build_information().get().await;
1602    ///
1603    ///     assert!(response.is_ok());
1604    ///
1605    ///     Ok(())
1606    /// }
1607    /// ```
1608    pub fn build_information(&self) -> BuildInformationQueryBuilder {
1609        BuildInformationQueryBuilder {
1610            client: self.clone(),
1611        }
1612    }
1613
1614    /// Retrieve Prometheus server runtime information.
1615    ///
1616    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#runtime-information)
1617    ///
1618    /// ```rust
1619    /// use prometheus_http_query::Client;
1620    ///
1621    /// #[tokio::main(flavor = "current_thread")]
1622    /// async fn main() -> Result<(), anyhow::Error> {
1623    ///     let client = Client::default();
1624    ///
1625    ///     let response = client.runtime_information().get().await;
1626    ///
1627    ///     assert!(response.is_ok());
1628    ///
1629    ///     Ok(())
1630    /// }
1631    /// ```
1632    pub fn runtime_information(&self) -> RuntimeInformationQueryBuilder {
1633        RuntimeInformationQueryBuilder {
1634            client: self.clone(),
1635        }
1636    }
1637
1638    /// Retrieve Prometheus TSDB statistics.
1639    ///
1640    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#tsdb-stats)
1641    ///
1642    /// ```rust
1643    /// use prometheus_http_query::Client;
1644    ///
1645    /// #[tokio::main(flavor = "current_thread")]
1646    /// async fn main() -> Result<(), anyhow::Error> {
1647    ///     let client = Client::default();
1648    ///
1649    ///     let response = client.tsdb_statistics().get().await;
1650    ///
1651    ///     assert!(response.is_ok());
1652    ///
1653    ///     Ok(())
1654    /// }
1655    /// ```
1656    pub fn tsdb_statistics(&self) -> TsdbStatisticsQueryBuilder {
1657        TsdbStatisticsQueryBuilder {
1658            client: self.clone(),
1659        }
1660    }
1661
1662    /// Retrieve WAL replay statistics.
1663    ///
1664    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#wal-replay-stats)
1665    ///
1666    /// ```rust
1667    /// use prometheus_http_query::Client;
1668    ///
1669    /// #[tokio::main(flavor = "current_thread")]
1670    /// async fn main() -> Result<(), anyhow::Error> {
1671    ///     let client = Client::default();
1672    ///
1673    ///     let response = client.wal_replay_statistics().get().await;
1674    ///
1675    ///     assert!(response.is_ok());
1676    ///
1677    ///     Ok(())
1678    /// }
1679    /// ```
1680    pub fn wal_replay_statistics(&self) -> WalReplayStatisticsQueryBuilder {
1681        WalReplayStatisticsQueryBuilder {
1682            client: self.clone(),
1683        }
1684    }
1685
1686    /// Query the current state of alertmanager discovery.
1687    ///
1688    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#alertmanagers)
1689    ///
1690    /// ```rust
1691    /// use prometheus_http_query::Client;
1692    ///
1693    /// #[tokio::main(flavor = "current_thread")]
1694    /// async fn main() -> Result<(), anyhow::Error> {
1695    ///     let client = Client::default();
1696    ///
1697    ///     let response = client.alertmanagers().get().await;
1698    ///
1699    ///     assert!(response.is_ok());
1700    ///
1701    ///     Ok(())
1702    /// }
1703    /// ```
1704    pub fn alertmanagers(&self) -> AlertmanagersQueryBuilder {
1705        AlertmanagersQueryBuilder {
1706            client: self.clone(),
1707        }
1708    }
1709
1710    /// Create a [`TargetMetadataQueryBuilder`] to apply filters to a target metadata
1711    /// query before sending it to Prometheus.
1712    ///
1713    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-target-metadata)
1714    ///
1715    /// ```rust
1716    /// use prometheus_http_query::{Client, Selector};
1717    ///
1718    /// #[tokio::main(flavor = "current_thread")]
1719    /// async fn main() -> Result<(), anyhow::Error> {
1720    ///     let client = Client::default();
1721    ///
1722    ///     // Retrieve metadata for a specific metric from all targets.
1723    ///     let response = client.target_metadata()
1724    ///         .metric("go_goroutines")
1725    ///         .get()
1726    ///         .await;
1727    ///
1728    ///     assert!(response.is_ok());
1729    ///
1730    ///     // Retrieve metric metadata from specific targets.
1731    ///     let response = client.target_metadata()
1732    ///         .match_target("{job=\"prometheus\"}")
1733    ///         .get()
1734    ///         .await;
1735    ///
1736    ///     assert!(response.is_ok());
1737    ///
1738    ///     // Retrieve metadata for a specific metric from targets that match a specific label set.
1739    ///     // Also use a stronger typed selector.
1740    ///     let s = Selector::new().eq("job", "node");
1741    ///     let response = client.target_metadata()
1742    ///         .metric("node_cpu_seconds_total")
1743    ///         .match_target(s)
1744    ///         .get()
1745    ///         .await;
1746    ///
1747    ///     assert!(response.is_ok());
1748    ///
1749    ///     Ok(())
1750    /// }
1751    /// ```
1752    pub fn target_metadata(&self) -> TargetMetadataQueryBuilder {
1753        TargetMetadataQueryBuilder {
1754            client: self.clone(),
1755            match_target: None,
1756            metric: None,
1757            limit: None,
1758        }
1759    }
1760
1761    /// Create a [`MetricMetadataQueryBuilder`] to apply filters to a metric metadata
1762    /// query before sending it to Prometheus.
1763    ///
1764    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-metric-metadata)
1765    ///
1766    /// ```rust
1767    /// use prometheus_http_query::Client;
1768    ///
1769    /// #[tokio::main(flavor = "current_thread")]
1770    /// async fn main() -> Result<(), anyhow::Error> {
1771    ///     let client = Client::default();
1772    ///
1773    ///     // Retrieve metadata for a all metrics.
1774    ///     let response = client.metric_metadata().get().await;
1775    ///
1776    ///     assert!(response.is_ok());
1777    ///
1778    ///     // Limit the number of returned metrics.
1779    ///     let response = client.metric_metadata().limit(100).get().await;
1780    ///
1781    ///     assert!(response.is_ok());
1782    ///
1783    ///     // Retrieve metadata for a specific metric but with a per-metric
1784    ///     // metadata limit.
1785    ///     let response = client.metric_metadata()
1786    ///         .metric("go_goroutines")
1787    ///         .limit_per_metric(5)
1788    ///         .get()
1789    ///         .await;
1790    ///
1791    ///     assert!(response.is_ok());
1792    ///
1793    ///     Ok(())
1794    /// }
1795    /// ```
1796    pub fn metric_metadata(&self) -> MetricMetadataQueryBuilder {
1797        MetricMetadataQueryBuilder {
1798            client: self.clone(),
1799            metric: None,
1800            limit: None,
1801            limit_per_metric: None,
1802        }
1803    }
1804
1805    /// Check Prometheus server health.
1806    ///
1807    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/management_api/#health-check)
1808    ///
1809    /// ```rust
1810    /// use prometheus_http_query::Client;
1811    ///
1812    /// #[tokio::main(flavor = "current_thread")]
1813    /// async fn main() -> Result<(), anyhow::Error> {
1814    ///     let client = Client::default();
1815    ///     assert!(client.is_server_healthy().await?);
1816    ///     Ok(())
1817    /// }
1818    /// ```
1819    pub async fn is_server_healthy(&self) -> Result<bool, Error> {
1820        let url = build_final_url(self.base_url.clone(), "-/healthy");
1821        self.client
1822            .get(url)
1823            .send()
1824            .await
1825            .map_err(|source| {
1826                Error::Client(ClientError {
1827                    message: "failed to send request to health endpoint",
1828                    source: Some(source),
1829                })
1830            })?
1831            .error_for_status()
1832            .map_err(|source| {
1833                Error::Client(ClientError {
1834                    message: "request to health endpoint returned an error",
1835                    source: Some(source),
1836                })
1837            })
1838            .map(|_| true)
1839    }
1840
1841    /// Check Prometheus server readiness.
1842    ///
1843    /// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/management_api/#readiness-check)
1844    ///
1845    /// ```rust
1846    /// use prometheus_http_query::Client;
1847    ///
1848    /// #[tokio::main(flavor = "current_thread")]
1849    /// async fn main() -> Result<(), anyhow::Error> {
1850    ///     let client = Client::default();
1851    ///     assert!(client.is_server_ready().await?);
1852    ///     Ok(())
1853    /// }
1854    /// ```
1855    pub async fn is_server_ready(&self) -> Result<bool, Error> {
1856        let url = build_final_url(self.base_url.clone(), "-/ready");
1857        self.client
1858            .get(url)
1859            .send()
1860            .await
1861            .map_err(|source| {
1862                Error::Client(ClientError {
1863                    message: "failed to send request to readiness endpoint",
1864                    source: Some(source),
1865                })
1866            })?
1867            .error_for_status()
1868            .map_err(|source| {
1869                Error::Client(ClientError {
1870                    message: "request to readiness endpoint returned an error",
1871                    source: Some(source),
1872                })
1873            })
1874            .map(|_| true)
1875    }
1876
1877    // Deserialize the raw reqwest response returned from the Prometheus server into a type `D` that implements serde's `Deserialize` trait.
1878    //
1879    // Internally, the response is deserialized into the [`ApiResponse`] type first.
1880    // On success, the data is returned as is. On failure, the error is mapped to the appropriate [`Error`] type.
1881    async fn deserialize<D: DeserializeOwned>(response: reqwest::Response) -> Result<D, Error> {
1882        let header = CONTENT_TYPE;
1883        if !util::is_json(response.headers().get(header)) {
1884            return Err(Error::Client(ClientError {
1885                message: "failed to parse response from server due to invalid media type",
1886                source: response.error_for_status().err(),
1887            }));
1888        }
1889        let response = response.json::<ApiResponse<D>>().await.map_err(|source| {
1890            Error::Client(ClientError {
1891                message: "failed to parse JSON response from server",
1892                source: Some(source),
1893            })
1894        })?;
1895        match response {
1896            ApiResponse::Success { data } => Ok(data),
1897            ApiResponse::Error(e) => Err(Error::Prometheus(e)),
1898        }
1899    }
1900}