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
//! The goal of this crate is to provide a query interface to the [Prometheus HTTP API](https://prometheus.io/docs/prometheus/latest/querying/api/) and leverage Rust's type system in the process. Thus mistakes while building a query can be caught at compile-time (or at least before actually sending the query to Prometheus).
//!
//! Most of the features of PromQL are mirrored in this library. Queries are gradually built from time series selectors, aggregations
//! and functions and then passed to an HTTP client to execute. Methods to retrieve various kinds of metadata and configuration are also implemented.
//!
//! The [Client] uses as [reqwest::Client] as HTTP client internally as you will see in the usage section. Thus its features and limitations also apply to this library.
//!
//! # Usage
//!
//! ## Initialize a client
//!
//! The [Client] can be constructed in various ways depending on your need to add customizations.
//!
//! ```rust
//! use prometheus_http_query::Client;
//! use std::str::FromStr;
//!
//! // In the most general case the default implementation is used to create the client.
//! // Requests will be sent to "http://127.0.0.1:9090 (the default listen address and port of the Prometheus server).
//! let client = Client::default();
//!
//! // Provide an alternative URL if you need to. The URL will be checked for correctness.
//! use std::convert::TryFrom;
//! let client = Client::try_from("https://prometheus.example.com").unwrap();
//!
//! // The greatest flexibility is offered by initializing a reqwest::Client first with
//! // all needed customizations and passing it along.
//! let client = {
//! let c = reqwest::Client::builder().no_proxy().build().unwrap();
//! Client::from(c, "https://prometheus.example.com").unwrap();
//! };
//! ```
//!
//! ## Construct PromQL queries
//!
//! Gradually build PromQL expressions using [Selector], turn it into a [RangeVector] or [InstantVector],
//! apply additional [aggregations] or [functions] on them and evaluate the final expression at an instant ([Client::query])
//! or a range of time ([Client::query_range]).
//!
//! ```rust
//! use prometheus_http_query::{Aggregate, Client, Error, InstantVector, Selector};
//! use prometheus_http_query::aggregations::{sum, topk};
//! use std::convert::TryInto;
//!
//! #[tokio::main(flavor = "current_thread")]
//! async fn main() -> Result<(), Error> {
//! let client = Client::default();
//!
//! let vector: InstantVector = Selector::new()
//! .metric("prometheus_http_requests_total")
//! .try_into()?;
//!
//! let q = topk(vector, Some(Aggregate::By(&["code"])), 5);
//!
//! let response = client.query(q, None, None).await?;
//!
//! assert!(response.as_instant().is_some());
//!
//! let vector: InstantVector = Selector::new()
//! .metric("prometheus_http_requests_total")
//! .with("code", "200")
//! .try_into()?;
//!
//! let q = sum(vector, None);
//!
//! let response = client.query(q, None, None).await?;
//!
//! if let Some(result) = response.as_instant() {
//! let first = result.get(0).unwrap();
//! println!("Received a total of {} HTTP requests", first.sample().value());
//! }
//! Ok(())
//! }
//! ```
//!
//! ## Custom non-validated PromQL queries
//!
//! It is also possible to bypass every kind of validation by supplying
//! a custom query directly to the [InstantVector] / [RangeVector] types.
//!
//! ```rust
//! use prometheus_http_query::{Client, Error, RangeVector};
//!
//! #[tokio::main(flavor = "current_thread")]
//! async fn main() -> Result<(), Error> {
//! let client = Client::default();
//!
//! let q = r#"sum by(cpu) (rate(node_cpu_seconds_total{mode="user"}[5m]))"#;
//!
//! let v = RangeVector(q.to_string());
//!
//! let response = client.query(v, None, None).await?;
//!
//! assert!(response.as_instant().is_some());
//!
//! Ok(())
//! }
//! ```
//!
//! ## Metadata queries
//!
//! Retrieve a list of time series that match a certain label set by providing one or more series [Selector]s.
//!
//! ```rust
//! use prometheus_http_query::{Client, Error, Selector};
//!
//! #[tokio::main(flavor = "current_thread")]
//! async fn main() -> Result<(), Error> {
//! let client = Client::default();
//!
//! 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 = client.series(&set, None, None).await;
//!
//! assert!(response.is_ok());
//!
//! Ok(())
//! }
//! ```
//!
//! ## Rules & Alerts
//!
//! Retrieve recording/alerting rules and active alerts.
//!
//! ```rust
//! use prometheus_http_query::{Client, Error, RuleType};
//!
//! #[tokio::main(flavor = "current_thread")]
//! async fn main() -> Result<(), Error> {
//! let client = Client::default();
//!
//! let response = client.rules(None).await;
//!
//! assert!(response.is_ok());
//!
//! // Only request alerting rules instead:
//! let response = client.rules(Some(RuleType::Alert)).await;
//!
//! assert!(response.is_ok());
//!
//! // Request active alerts:
//! let response = client.alerts().await;
//!
//! assert!(response.is_ok());
//!
//! Ok(())
//! }
//! ```
//!
//! These are a few examples. See [Client] for examples of other types of metadata queries.
//!
//! # Compatibility
//!
//! This version of the crate is compatible with Prometheus server >= v2.31.
//! Versions as "old" as v2.26 are compatible as well when some features are not used. For example trigonometric functions
//! were only introduced with v2.31. [Client::targets] will fail as well because the result as returned by the API
//! changed between v2.26 and v2.31.
//!
//! # Supported operations
//!
//! - [x] Building PromQL expressions using time series selectors, functions and operators (aggregation/binary/vector matching ...)
//! - [x] Evaluating expressions as instant queries
//! - [x] Evaluating expressions as range queries
//! - [x] Executing series metadata queries
//! - [x] Executing label metadata queries (names/values)
//! - [x] Retrieving target discovery status
//! - [x] Retrieve alerting + recording rules
//! - [x] Retrieve active alerts
//! - [x] Retrieve configured flags & values
//! - [x] Target metadata
//! - [x] Metric metadata
//! - [x] Alertmanager service discovery status
//! - [ ] Prometheus config
//! - [ ] Prometheus runtime & build information
//!
//! # Notes
//!
//! ## On parsing an error handling
//!
//! If the JSON response from the Prometheus HTTP API indicates an error (field `status` == `"error"`),
//! then the contents of both fields `errorType` and `error` are captured and then returned by the client
//! as a variant of the [Error] enum, just as any HTTP errors (non-200) that may indicate a problem
//! with the provided query string. Thus any syntax problems etc. that cannot be caught at compile time
//! or before executing the query will at least be propagated as returned by the HTTP API.
//!
//! ## On types
//!
//! This library uses two versions of instant vector and range vector types. [InstantVector] to build queries and be passed to [Client::query] or [Client::query_range] to execute. And [crate::response::InstantVector] as part of the result of these methods. The same applies to range vectors.
//!
//! # Limitations
//!
//! * Subqueries are not supported (only as custom query)
//! * PromQL functions that do not take a range / instant vector as an argument are not supported (only as custom query), e.g. pi()
//! * The [String](https://prometheus.io/docs/prometheus/latest/querying/api/#strings) result type is not supported
pub mod aggregations;
mod client;
mod error;
pub mod functions;
pub mod response;
mod selector;
mod util;
mod vector;
pub use self::client::Client;
pub use self::error::Error;
pub use self::selector::Selector;
pub use self::util::Aggregate;
pub use self::util::Group;
pub use self::util::Match;
pub use self::util::RuleType;
pub use self::util::TargetState;
pub use self::vector::InstantVector;
pub use self::vector::RangeVector;