use std::borrow::Cow;
use memchr::memchr2;
use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::path::key_part;
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
const TYPES: [&str; 9] = [
"counter",
"gauge",
"histogram",
"gaugehistogram",
"summary",
"untyped",
"unknown",
"stateset",
"info",
];
fn suffixes(kind: &str) -> &'static [&'static str] {
match kind {
"counter" => &["_total", "_created"],
"histogram" => &["_bucket", "_count", "_sum", "_created"],
"gaugehistogram" => &["_bucket", "_gcount", "_gsum"],
"summary" => &["_count", "_sum", "_created"],
"info" => &["_info"],
_ => &[],
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Line {
Directive,
Comment,
Sample(usize),
}
#[derive(Debug, Clone)]
pub struct Prometheus {
signature: Signature,
}
impl Default for Prometheus {
fn default() -> Self {
Self::new()
}
}
impl Prometheus {
#[must_use]
pub fn new() -> Self {
let signature = Signature::builder()
.build()
.unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
Self { signature }
}
}
impl Parser for Prometheus {
fn hands_on_body(&self) -> bool {
false
}
fn name(&self) -> &'static str {
"prometheus"
}
fn tier(&self) -> MatcherTier {
MatcherTier::Field
}
fn signature(&self) -> &Signature {
&self.signature
}
fn parse<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
let mark = out.mark();
let read = match read_line(input)? {
Read::Comment => return Ok(Parsed::NoMatch),
Read::Directive(d) => {
out.field("name", text_value(d.name));
out.field(d.kind.field(), text_value(d.text));
Ok(())
}
Read::Sample(at) => write_sample(input, at, out).map(drop),
};
read.map(|()| Parsed::Done)
.inspect_err(|_| out.rollback(mark))
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PrometheusReader {
family: Option<Family>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Family {
pub name: String,
pub kind: Option<&'static str>,
pub help: Option<String>,
pub unit: Option<String>,
}
impl PrometheusReader {
#[must_use]
pub const fn new() -> Self {
Self { family: None }
}
#[must_use]
pub const fn family(&self) -> Option<&Family> {
self.family.as_ref()
}
pub fn line<'a>(
&mut self,
line: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Line, ParseError> {
let at = match read_line(line)? {
Read::Comment => return Ok(Line::Comment),
Read::Directive(d) => {
self.directive(&d);
return Ok(Line::Directive);
}
Read::Sample(at) => at,
};
let mark = out.mark();
let (name, mut written) = match write_sample(line, at, out) {
Ok(read) => read,
Err(e) => {
out.rollback(mark);
return Err(e);
}
};
if let Some(family) = &self.family
&& let Some(kind) = family.kind
&& belongs(&name, &family.name, kind)
{
out.field("type", FieldValue::borrowed(kind.as_bytes(), Hint::Text));
written += 1;
}
Ok(Line::Sample(written))
}
fn directive(&mut self, d: &Directive<'_>) {
if self.family.as_ref().is_some_and(|f| f.name != *d.name) {
self.family = None;
}
let family = self.family.get_or_insert_with(|| Family {
name: d.name.clone().into_owned(),
..Family::default()
});
match d.kind {
Kind::Help => family.help = Some(d.text.clone().into_owned()),
Kind::Unit => family.unit = Some(d.text.clone().into_owned()),
Kind::Type => family.kind = TYPES.iter().copied().find(|t| *t == d.text),
}
}
}
fn belongs(sample: &str, family: &str, kind: &str) -> bool {
sample
.strip_prefix(family)
.is_some_and(|rest| rest.is_empty() || suffixes(kind).contains(&rest))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Help,
Type,
Unit,
}
impl Kind {
const fn field(self) -> &'static str {
match self {
Self::Help => "help",
Self::Type => "type",
Self::Unit => "unit",
}
}
}
#[derive(Debug)]
struct Directive<'a> {
kind: Kind,
name: Cow<'a, str>,
text: Cow<'a, str>,
}
enum Read<'a> {
Comment,
Directive(Directive<'a>),
Sample(usize),
}
const fn blank(b: u8) -> bool {
b == b' ' || b == b'\t'
}
fn text_value(text: Cow<'_, str>) -> FieldValue<'_> {
match text {
Cow::Borrowed(t) => FieldValue::borrowed(t.as_bytes(), Hint::Text),
Cow::Owned(t) => FieldValue::owned(t.into_bytes(), Hint::Text),
}
}
const fn malformed(offset: usize, reason: &'static str) -> ParseError {
ParseError::Malformed { offset, reason }
}
fn read_line(line: &[u8]) -> Result<Read<'_>, ParseError> {
let mut c = Cursor { s: line, i: 0 };
c.blanks();
match c.peek() {
None | Some(b'\r') if c.rest().iter().all(|&b| blank(b) || b == b'\r') => Ok(Read::Comment),
Some(b'#') => {
c.i += 1;
if c.blanks() == 0 {
return Ok(Read::Comment);
}
let word = c.word();
let kind = match word {
b"HELP" => Kind::Help,
b"TYPE" => Kind::Type,
b"UNIT" => Kind::Unit,
_ => return Ok(Read::Comment),
};
if c.blanks() == 0 {
return Err(malformed(c.i, "a directive with no metric name"));
}
let name = c.metric_name()?;
let text = if c.blanks() == 0 {
if c.at_end() {
Cow::Borrowed("")
} else {
return Err(malformed(c.i, "text joined to a directive's name"));
}
} else {
let rest = c.rest_trimmed();
let text = std::str::from_utf8(rest).map_err(|e| {
malformed(c.i + e.valid_up_to(), "a directive that isn't UTF-8")
})?;
match kind {
Kind::Help => unescape_help(text),
_ => Cow::Borrowed(text),
}
};
if kind == Kind::Type && !TYPES.contains(&&*text) {
return Err(malformed(c.i, "a # TYPE naming no metric type"));
}
Ok(Read::Directive(Directive { kind, name, text }))
}
_ => Ok(Read::Sample(c.i)),
}
}
fn unescape_help(text: &str) -> Cow<'_, str> {
if !text.contains('\\') {
return Cow::Borrowed(text);
}
let mut out = String::with_capacity(text.len());
let mut chars = text.chars();
while let Some(ch) = chars.next() {
if ch != '\\' {
out.push(ch);
continue;
}
match chars.next() {
Some('n') => out.push('\n'),
Some('\\') | None => out.push('\\'),
Some(other) => {
out.push('\\');
out.push(other);
}
}
}
Cow::Owned(out)
}
fn write_sample<'a>(
line: &'a [u8],
at: usize,
out: &mut dyn FieldSink<'a>,
) -> Result<(Cow<'a, str>, usize), ParseError> {
let mut c = Cursor { s: line, i: at };
let mut name = if c.peek() == Some(b'{') {
None
} else {
Some(c.metric_name()?)
};
let before = c.i;
c.blanks();
let mut written = 1;
if c.peek() == Some(b'{') {
out.push_prefix("labels.");
let read = c.labels(out, &mut name);
out.pop_prefix();
written += read?;
} else {
c.i = before;
}
let name = name.ok_or_else(|| malformed(at, "a sample with no metric name"))?;
out.field("name", text_value(name.clone()));
written += c.value_and_time(out)?;
if c.blanks() > 0 && c.peek() == Some(b'#') {
c.i += 1;
if c.blanks() == 0 || c.peek() != Some(b'{') {
return Err(malformed(c.i, "an exemplar with no labels"));
}
out.push_prefix("exemplar.");
let read = c.exemplar(out);
out.pop_prefix();
written += read?;
}
c.blanks();
if !c.at_end() {
return Err(malformed(c.i, "text after a sample"));
}
Ok((name, written))
}
struct Cursor<'a> {
s: &'a [u8],
i: usize,
}
impl<'a> Cursor<'a> {
fn peek(&self) -> Option<u8> {
self.s.get(self.i).copied()
}
fn rest(&self) -> &'a [u8] {
&self.s[self.i.min(self.s.len())..]
}
fn at_end(&self) -> bool {
matches!(self.rest(), [] | [b'\r'])
}
fn rest_trimmed(&self) -> &'a [u8] {
let rest = self.rest();
let end = rest
.iter()
.rposition(|&b| !blank(b) && b != b'\r')
.map_or(0, |p| p + 1);
&rest[..end]
}
fn blanks(&mut self) -> usize {
let start = self.i;
while self.peek().is_some_and(blank) {
self.i += 1;
}
self.i - start
}
fn word(&mut self) -> &'a [u8] {
let start = self.i;
while self.peek().is_some_and(|b| !blank(b)) {
self.i += 1;
}
let mut word = &self.s[start..self.i];
if self.i == self.s.len()
&& let [head @ .., b'\r'] = word
{
word = head;
self.i -= 1;
}
word
}
fn name(&mut self, metric: bool) -> Result<Cow<'a, str>, ParseError> {
if self.peek() == Some(b'"') {
let name = self.quoted()?;
return if name.is_empty() {
Err(malformed(self.i, "an empty quoted name"))
} else {
Ok(name)
};
}
let start = self.i;
let ok = |b: u8, first: bool| {
b.is_ascii_alphabetic()
|| b == b'_'
|| (metric && b == b':')
|| (!first && b.is_ascii_digit())
};
if !self.peek().is_some_and(|b| ok(b, true)) {
return Err(malformed(start, "no metric or label name"));
}
while self.peek().is_some_and(|b| ok(b, false)) {
self.i += 1;
}
Ok(Cow::Borrowed(
std::str::from_utf8(&self.s[start..self.i]).unwrap_or_default(),
))
}
fn metric_name(&mut self) -> Result<Cow<'a, str>, ParseError> {
self.name(true)
}
fn quoted(&mut self) -> Result<Cow<'a, str>, ParseError> {
let open = self.i;
self.i += 1;
let start = self.i;
let mut owned: Option<Vec<u8>> = None;
let mut copied = start;
loop {
let Some(at) = memchr2(b'"', b'\\', self.rest()) else {
return Err(malformed(open, "a quoted string with no closing quote"));
};
self.i += at;
if self.s[self.i] == b'"' {
break;
}
let Some(&next) = self.s.get(self.i + 1) else {
return Err(malformed(open, "a quoted string with no closing quote"));
};
let undone = match next {
b'\\' => Some(b'\\'),
b'"' => Some(b'"'),
b'n' => Some(b'\n'),
_ => None,
};
if let Some(byte) = undone {
let buf = owned.get_or_insert_with(Vec::new);
buf.extend_from_slice(&self.s[copied..self.i]);
buf.push(byte);
copied = self.i + 2;
}
self.i += 2;
}
let end = self.i;
self.i += 1;
let bytes: Cow<'a, [u8]> = match owned {
None => Cow::Borrowed(&self.s[start..end]),
Some(mut buf) => {
buf.extend_from_slice(&self.s[copied..end]);
Cow::Owned(buf)
}
};
match bytes {
Cow::Borrowed(b) => std::str::from_utf8(b).map(Cow::Borrowed).ok(),
Cow::Owned(b) => String::from_utf8(b).map(Cow::Owned).ok(),
}
.ok_or_else(|| malformed(start, "a quoted string that isn't UTF-8"))
}
fn labels(
&mut self,
out: &mut dyn FieldSink<'a>,
metric: &mut Option<Cow<'a, str>>,
) -> Result<usize, ParseError> {
self.i += 1;
let mut written = 0;
loop {
self.blanks();
if self.peek() == Some(b'}') {
self.i += 1;
return Ok(written);
}
let quoted = self.peek() == Some(b'"');
let at = self.i;
let name = self.name(false)?;
self.blanks();
match self.peek() {
Some(b'=') => {
self.i += 1;
self.blanks();
if self.peek() != Some(b'"') {
return Err(malformed(self.i, "a label value that isn't quoted"));
}
let value = self.quoted()?;
out.field(&key_part(name), text_value(value));
written += 1;
}
Some(b',' | b'}') if quoted && metric.is_none() => *metric = Some(name),
_ => return Err(malformed(at, "a label with no `=`")),
}
self.blanks();
match self.peek() {
Some(b',') => self.i += 1,
Some(b'}') => {}
_ => return Err(malformed(self.i, "labels with no `,` or `}` between them")),
}
}
}
fn value_and_time(&mut self, out: &mut dyn FieldSink<'a>) -> Result<usize, ParseError> {
if self.blanks() == 0 {
return Err(malformed(self.i, "a sample with no value"));
}
let at = self.i;
let value = self.word();
if !is_float(value) {
return Err(malformed(at, "a sample value that isn't a number"));
}
out.field("value", FieldValue::borrowed(value, Hint::Float));
let before = self.i;
if self.blanks() == 0 || self.at_end() || self.peek() == Some(b'#') {
self.i = before;
return Ok(1);
}
let at = self.i;
let time = self.word();
let hint = if is_int(time) {
Hint::Int
} else if is_float(time) {
Hint::Float
} else {
return Err(malformed(at, "a timestamp that isn't a number"));
};
out.field("timestamp", FieldValue::borrowed(time, hint));
Ok(2)
}
fn exemplar(&mut self, out: &mut dyn FieldSink<'a>) -> Result<usize, ParseError> {
let mut none = Some(Cow::Borrowed(""));
out.push_prefix("labels.");
let read = self.labels(out, &mut none);
out.pop_prefix();
Ok(read? + self.value_and_time(out)?)
}
}
fn is_int(text: &[u8]) -> bool {
let digits = text
.strip_prefix(b"-")
.or_else(|| text.strip_prefix(b"+"))
.unwrap_or(text);
!digits.is_empty() && digits.iter().all(u8::is_ascii_digit)
}
fn is_float(text: &[u8]) -> bool {
std::str::from_utf8(text).is_ok_and(|t| t.parse::<f64>().is_ok())
}
#[cfg(test)]
mod tests;