use std::collections::{HashMap, HashSet};
use std::fmt;
use std::time::{Duration, SystemTime};
use super::Metrics;
use super::describe::Description;
use super::ingest::{ONE_TEXT, SAMPLE_BYTES, within};
use super::instruments::{MOST_HELP, MOST_UNIT};
use super::labels::NAME;
use super::series::{Kind, Labels, Sample, Series};
use crate::clock::from_unix_millis;
use crate::{Error, Result, unix_millis};
#[derive(Clone, Debug)]
#[must_use = "a text is written by ingest"]
pub struct Prometheus {
metrics: Metrics,
labels: Labels,
at: Option<SystemTime>,
keep: Option<Duration>,
}
impl Metrics {
pub fn prometheus(&self) -> Prometheus {
Prometheus { metrics: self.clone(), labels: Labels::new(), at: None, keep: None }
}
}
impl Prometheus {
pub fn label(mut self, name: impl Into<String>, value: impl fmt::Display) -> Prometheus {
self.labels.insert(name.into(), value.to_string());
self
}
pub fn at(mut self, at: SystemTime) -> Prometheus {
self.at = Some(at);
self
}
pub fn keep(mut self, keep: Duration) -> Prometheus {
self.keep = Some(keep);
self
}
pub fn ingest(&self, text: impl AsRef<[u8]>) -> Result<()> {
let engine = &self.metrics.engine;
let read = self.read(text.as_ref())?;
engine.ingest_held(engine.check_within(&read.series, ONE_TEXT)?.described(read.described))
}
#[cfg(feature = "async")]
pub(crate) fn check(&self, text: &[u8]) -> Result<super::ingest::Checked> {
let read = self.read(text)?;
Ok(self.metrics.engine.check_within(&read.series, ONE_TEXT)?.described(read.described))
}
#[cfg(feature = "async")]
pub(crate) fn timed(mut self) -> Prometheus {
if self.at.is_none() {
self.at = Some(crate::clock::from_unix_millis(self.metrics.engine.now()));
}
self
}
fn read(&self, text: &[u8]) -> Result<Exposition> {
let at = self.at.map_or_else(|| self.metrics.engine.now(), unix_millis);
let mut read = parse(text, &self.labels, at)?;
if let Some(keep) = self.keep {
read.series.iter_mut().for_each(|series| series.keep = Some(keep));
}
Ok(read)
}
}
#[derive(Debug)]
pub(super) struct Exposition {
pub(super) series: Vec<Series>,
pub(super) described: Vec<(String, Description)>,
}
const BLANK: [char; 2] = [' ', '\t'];
const EOF: &str = "# EOF";
const QUOTED: usize = 64;
pub(super) fn parse(text: &[u8], given: &Labels, at: i64) -> Result<Exposition> {
let text = text.strip_prefix(b"\xef\xbb\xbf").unwrap_or(text);
let mut reader = Reader::new(given, at, is_open_metrics(text));
for (index, line) in text.split(|byte| *byte == b'\n').enumerate() {
let number = index + 1;
let line =
std::str::from_utf8(line).map_err(|_| Error::invalid(format!("metrics: line {number}: not UTF-8")))?;
let line = line.trim_ascii();
reader.line(line).map_err(|error| error.within(format!("metrics: line {number}, `{}`", excerpt(line))))?;
}
let described = reader.described();
Ok(Exposition { series: reader.series, described })
}
fn is_open_metrics(text: &[u8]) -> bool {
let last = text.split(|byte| *byte == b'\n').map(<[u8]>::trim_ascii).rfind(|line| !line.is_empty());
last == Some(EOF.as_bytes())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Type {
Counter,
Gauge,
Histogram,
GaugeHistogram,
Summary,
Info,
StateSet,
Unknown,
}
const TYPES: [(&str, Type); 9] = [
("counter", Type::Counter),
("gauge", Type::Gauge),
("histogram", Type::Histogram),
("gaugehistogram", Type::GaugeHistogram),
("summary", Type::Summary),
("info", Type::Info),
("stateset", Type::StateSet),
("untyped", Type::Unknown),
("unknown", Type::Unknown),
];
const SUFFIXES: [&str; 8] = ["_total", "_created", "_bucket", "_sum", "_count", "_info", "_gsum", "_gcount"];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Role {
Written(Kind),
LeftOut,
Stranger,
}
impl Type {
fn role(self, suffix: &str) -> Role {
use Type::{Counter, Gauge, GaugeHistogram, Histogram, Info, StateSet, Summary, Unknown};
match (self, suffix) {
(Counter | Histogram | Summary, "_created") => Role::LeftOut,
(Counter, "" | "_total") | (Histogram | Summary, "_sum" | "_count") => Role::Written(Kind::Counter),
(Histogram, "_bucket") => Role::Written(Kind::Histogram),
(Gauge | Summary | StateSet | Unknown, "")
| (Info, "" | "_info")
| (GaugeHistogram, "_bucket" | "_gsum" | "_gcount") => Role::Written(Kind::Gauge),
_ => Role::Stranger,
}
}
fn word(self) -> &'static str {
TYPES.iter().find(|(_, given)| *given == self).map_or("unknown", |(word, _)| word)
}
}
struct Reader<'a> {
given: &'a Labels,
at: i64,
open_metrics: bool,
families: HashMap<String, Type>,
descriptions: HashMap<String, Description>,
untyped: HashSet<String>,
series: Vec<Series>,
bytes: usize,
ended: bool,
}
impl<'a> Reader<'a> {
fn new(given: &'a Labels, at: i64, open_metrics: bool) -> Self {
let (families, descriptions, untyped) = (HashMap::new(), HashMap::new(), HashSet::new());
Reader { given, at, open_metrics, families, descriptions, untyped, series: Vec::new(), bytes: 0, ended: false }
}
fn line(&mut self, line: &str) -> Result<()> {
if line.is_empty() {
return Ok(());
}
if self.ended {
return Err(Error::invalid("a line after `# EOF`, which ends the text"));
}
match line.strip_prefix('#') {
Some(_) if line == EOF => {
self.ended = true;
Ok(())
}
Some(comment) => self.comment(comment),
None => self.sample(line),
}
}
fn comment(&mut self, comment: &str) -> Result<()> {
let (keyword, rest) = comment.trim_start_matches(BLANK).split_once(BLANK).unwrap_or((comment.trim(), ""));
match keyword {
"TYPE" => self.type_line(rest),
"HELP" | "UNIT" => {
self.describe(keyword, rest);
Ok(())
}
_ => Ok(()),
}
}
fn type_line(&mut self, rest: &str) -> Result<()> {
let line = || Error::invalid("a type's line is `# TYPE`, a metric's name and its type");
let (name, rest) = metric_name(rest).map_err(|error| if rest.trim().is_empty() { line() } else { error })?;
let mut words = rest.split(BLANK).filter(|word| !word.is_empty());
let (Some(word), None) = (words.next(), words.next()) else { return Err(line()) };
self.declare(&name, word)
}
fn describe(&mut self, keyword: &str, rest: &str) {
let Ok((name, text)) = metric_name(rest) else { return };
let text = text.trim_matches(BLANK);
let description = self.descriptions.entry(name).or_default();
if keyword == "HELP" {
let help = unescaped(text);
if help.len() <= MOST_HELP {
description.help = help;
}
} else if text.len() <= MOST_UNIT && !text.contains(BLANK) {
description.unit = text.to_owned();
}
}
fn described(&self) -> Vec<(String, Description)> {
let mut names: Vec<&str> = self.series.iter().map(|series| series.name.as_str()).collect();
names.sort_unstable();
names.dedup();
let of_family = |name: &str| {
let family = self.family_of(name).map_or(name, |(family, _)| family);
let given = self.descriptions.get(family)?;
let in_unit = matches!(&name[family.len()..], "" | "_total" | "_sum" | "_gsum");
let unit = if in_unit { given.unit.clone() } else { String::new() };
let described = Description { unit, help: given.help.clone() };
(described != Description::default()).then(|| (name.to_owned(), described))
};
names.into_iter().filter_map(of_family).collect()
}
fn declare(&mut self, name: &str, word: &str) -> Result<()> {
let family = TYPES.iter().find(|(given, _)| *given == word).map(|(_, family)| *family).ok_or_else(|| {
Error::invalid(format!(
"a type {word:?}: counter, gauge, histogram, summary or untyped, \
or OpenMetrics' gaugehistogram, info, stateset or unknown"
))
})?;
if self.families.contains_key(name) {
return Err(Error::invalid(format!("a second `# TYPE` of {name}")));
}
let written_before =
|suffix: &&&str| family.role(suffix) != Role::Stranger && self.untyped.contains(&format!("{name}{suffix}"));
if let Some(suffix) = [""].iter().chain(&SUFFIXES).find(written_before) {
return Err(Error::invalid(format!("the `# TYPE` of {name} after its sample {name}{suffix}")));
}
self.families.insert(name.to_owned(), family);
Ok(())
}
fn sample(&mut self, line: &str) -> Result<()> {
let (classic, rest) = name_at(line, true);
let (quoted, labels, rest) = labels_of(rest)?;
let name = match (classic, quoted) {
("", Some(quoted)) => quoted,
("", None) => {
return Err(Error::invalid(format!("a sample's line begins with its metric's name: {NAMED}")));
}
(classic, None) => classic.to_owned(),
(classic, Some(quoted)) => {
return Err(Error::invalid(format!("a sample of two names, {classic} and {quoted:?}")));
}
};
let name = name.as_str();
let (value, at) = self.value_and_time(rest)?;
let Some(kind) = self.kind_of(name)? else { return Ok(()) };
let labels = self.with_given(labels)?;
self.bytes += NAME.len() + name.len() + SAMPLE_BYTES;
self.bytes += labels.iter().map(|(label, value)| label.len() + value.len()).sum::<usize>();
within(ONE_TEXT, "a text", self.series.len() + 1, self.bytes)?;
let samples = vec![Sample { at: from_unix_millis(at), value }];
self.series.push(Series { name: name.to_owned(), kind, labels, samples, keep: None });
Ok(())
}
fn kind_of(&mut self, name: &str) -> Result<Option<Kind>> {
match (self.family_of(name).map(|(_, role)| role), self.families.get(name)) {
(Some(Role::Written(kind)), _) => Ok(Some(kind)),
(Some(_), _) => Ok(None),
(None, Some(&family)) => {
let (sum, count) = if family == Type::Histogram { ("_sum", "_count") } else { ("_gsum", "_gcount") };
let word = family.word();
Err(Error::invalid(format!(
"{name} is a {word}, whose samples are {name}_bucket, {name}{sum} and {name}{count}"
)))
}
(None, None) => {
if !self.untyped.contains(name) {
self.untyped.insert(name.to_owned());
}
Ok(Some(Kind::Gauge))
}
}
}
fn family_of<'n>(&self, name: &'n str) -> Option<(&'n str, Role)> {
[""].iter().chain(&SUFFIXES).find_map(|suffix| {
let family = name.strip_suffix(suffix)?;
let role = self.families.get(family)?.role(suffix);
(role != Role::Stranger).then_some((family, role))
})
}
fn with_given(&self, mut labels: Labels) -> Result<Labels> {
for (label, value) in self.given {
if labels.contains_key(label) {
return Err(Error::invalid(format!("label {label}, which the call gives every series")));
}
labels.insert(label.clone(), value.clone());
}
Ok(labels)
}
fn value_and_time(&self, rest: &str) -> Result<(f64, i64)> {
if !rest.is_empty() && !rest.starts_with(BLANK) {
return Err(Error::invalid(format!("a space between the name and the value, where {NAMED}")));
}
let mut words = rest.split(BLANK).filter(|word| !word.is_empty()).take_while(|word| !word.starts_with('#'));
let value = value_of(words.next().ok_or_else(|| Error::invalid("a sample without its value"))?)?;
let at = words.next().map_or(Ok(self.at), |word| self.time_of(word))?;
if let Some(word) = words.next() {
return Err(Error::invalid(format!("{word:?} after the sample's time")));
}
Ok((value, at))
}
fn time_of(&self, word: &str) -> Result<i64> {
if !self.open_metrics {
return word.parse().map_err(|_| {
Error::invalid(format!(
"a time {word:?}: milliseconds, an integer; OpenMetrics' seconds come in a text that ends `# EOF`"
))
});
}
let millis = word.parse::<f64>().map(|seconds| (seconds * 1000.0).round());
millis
.ok()
.filter(|millis| millis.abs() < 9.2e18)
.map(|millis| millis as i64)
.ok_or_else(|| Error::invalid(format!("a time {word:?}: OpenMetrics' seconds since 1970, a number")))
}
}
const NAMED: &str = "a name holds letters, digits, `_` and a metric's `:`, and begins with no digit, or is quoted";
fn metric_name(text: &str) -> Result<(String, &str)> {
let text = text.trim_start_matches(BLANK);
if text.starts_with('"') {
let (name, rest) = quoted(text, "a metric's name")?;
if name.is_empty() {
return Err(Error::invalid("a metric's name of no character"));
}
return Ok((name, rest));
}
let (name, rest) = name_at(text, true);
if name.is_empty() || !(rest.is_empty() || rest.starts_with(BLANK)) {
let word = text.split(BLANK).next().unwrap_or(text);
return Err(Error::invalid(format!("a metric's name {word:?}: {NAMED}")));
}
Ok((name.to_owned(), rest))
}
fn name_at(text: &str, metric: bool) -> (&str, &str) {
let named = |(at, byte): &(usize, u8)| {
byte.is_ascii_alphabetic() || *byte == b'_' || (metric && *byte == b':') || (*at > 0 && byte.is_ascii_digit())
};
let end = text.bytes().enumerate().find(|pair| !named(pair)).map_or(text.len(), |(at, _)| at);
text.split_at(end)
}
fn labels_of(rest: &str) -> Result<(Option<String>, Labels, &str)> {
let Some(mut rest) = rest.trim_start_matches(BLANK).strip_prefix('{') else {
return Ok((None, Labels::new(), rest));
};
let (mut name, mut labels, mut empty) = (None, Labels::new(), Vec::new());
let mut first = true;
loop {
rest = rest.trim_start_matches(BLANK);
if let Some(after) = rest.strip_prefix('}') {
return Ok((name, labels, after));
}
let (label, after) = label_name(rest)?;
let after = after.trim_start_matches(BLANK);
let Some(after) = after.strip_prefix('=') else {
if !(first && rest.starts_with('"')) {
return Err(Error::invalid(format!("label {label} without `=` and its value")));
}
name = Some(label);
(rest, first) = (next_in_braces(after, "the metric's quoted name")?, false);
continue;
};
first = false;
let (value, after) = quoted(after.trim_start_matches(BLANK), &format!("label {label}"))?;
if labels.contains_key(&label) || empty.contains(&label) {
return Err(Error::invalid(format!("label {label} twice")));
}
let what = format!("label {label}'s value");
if value.is_empty() {
empty.push(label);
} else {
labels.insert(label, value);
}
rest = next_in_braces(after, &what)?;
}
}
fn label_name(rest: &str) -> Result<(String, &str)> {
if rest.starts_with('"') {
let (name, after) = quoted(rest, "a quoted name")?;
if name.is_empty() {
return Err(Error::invalid("a quoted name of no character"));
}
return Ok((name, after));
}
let (label, after) = name_at(rest, false);
if label.is_empty() {
return Err(Error::invalid(format!("a label's name, where {NAMED}")));
}
Ok((label.to_owned(), after))
}
fn next_in_braces<'a>(rest: &'a str, what: &str) -> Result<&'a str> {
let rest = rest.trim_start_matches(BLANK);
match rest.strip_prefix(',') {
Some(after) => Ok(after),
None if rest.starts_with('}') => Ok(rest),
None => Err(Error::invalid(format!("{what} followed by neither `,` nor `}}`"))),
}
}
fn quoted<'a>(rest: &'a str, what: &str) -> Result<(String, &'a str)> {
let refused = |problem| Error::invalid(format!("{what}: {problem}"));
let mut rest = rest.strip_prefix('"').ok_or_else(|| refused("a value between double quotes"))?;
let mut value = String::new();
while let Some(at) = rest.find(['"', '\\']) {
value.push_str(&rest[..at]);
if rest.as_bytes()[at] == b'"' {
return Ok((value, &rest[at + 1..]));
}
let mut escaped = rest[at + 1..].chars();
match escaped.next() {
Some('n') => value.push('\n'),
Some(character @ ('\\' | '"')) => value.push(character),
Some(other) => value.extend(['\\', other]),
None => break,
}
rest = escaped.as_str();
}
Err(refused("a value without its closing quote"))
}
fn unescaped(text: &str) -> String {
let mut help = String::with_capacity(text.len());
let mut characters = text.chars();
while let Some(character) = characters.next() {
match (character, characters.clone().next()) {
('\\', Some(escaped @ ('\\' | '"'))) => help.push(escaped),
('\\', Some('n')) => help.push('\n'),
_ => {
help.push(character);
continue;
}
}
characters.next();
}
help
}
fn value_of(word: &str) -> Result<f64> {
let refused = |what: &str| Error::invalid(format!("a value {word:?}: {what}"));
let value: f64 = word.parse().map_err(|_| refused("a number, +Inf, -Inf or NaN"))?;
let infinity =
word.trim_start_matches(['+', '-']).as_bytes().first().is_some_and(|byte| byte.eq_ignore_ascii_case(&b'i'));
if value.is_infinite() && !infinity {
return Err(refused("past the largest float"));
}
Ok(value)
}
fn excerpt(line: &str) -> String {
if line.len() <= QUOTED {
return line.to_owned();
}
let end = (0..=QUOTED).rev().find(|end| line.is_char_boundary(*end)).unwrap_or(0);
format!("{}…", &line[..end])
}
#[cfg(test)]
#[path = "prometheus_tests.rs"]
mod tests;