chadtmiller.com/monolith
An atproto PDS
0
0
// Prometheus' text exposition format, version 0.0.4, read strictly
// (spec/OPERATIONS.md).
const NAME = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/
const LABEL = /^[a-zA-Z_][a-zA-Z0-9_]*$/
/// Read an exposition. Answers `{families, errors}`: `families` by name,
/// each `{type, help, samples: [{name, labels, value}]}`; `errors` what does
/// not follow the format.
export function parseMetrics(text) {
const families = {}
const errors = []
const family = (name) => (families[name] ??= { type: null, help: null, samples: [] })
// The family a sample is of: a histogram's `_bucket`, `_sum` and `_count`
// are of the histogram.
const owner = (name) => {
for (const suffix of ['_bucket', '_sum', '_count']) {
const base = name.slice(0, -suffix.length)
if (name.endsWith(suffix) && families[base]?.type === 'histogram') return base
}
return name
}
if (text.length && !text.endsWith('\n')) errors.push('the exposition does not end with a newline')
for (const [i, line] of text.split('\n').entries()) {
if (!line.trim()) continue
const at = `line ${i + 1}: ${line.slice(0, 120)}`
if (line.startsWith('#')) {
const m = /^# (HELP|TYPE) (\S+) ?(.*)$/.exec(line)
if (!m) continue
if (!NAME.test(m[2])) errors.push(`${at}: not a metric name`)
const f = family(m[2])
if (m[1] === 'HELP') f.help = m[3]
else {
if (!['counter', 'gauge', 'histogram', 'summary', 'untyped'].includes(m[3])) errors.push(`${at}: not a type`)
if (f.samples.length) errors.push(`${at}: TYPE after the family's samples`)
f.type = m[3]
}
continue
}
const m = /^([a-zA-Z_:][a-zA-Z0-9_:]*)(\{(.*)\})? ([^ ]+)( -?\d+)?$/.exec(line)
if (!m) {
errors.push(`${at}: not a sample`)
continue
}
const labels = {}
if (m[3] !== undefined) {
const re = /\s*([a-zA-Z_][a-zA-Z0-9_]*)="((?:[^"\\]|\\.)*)"\s*(,|$)/y
let j = 0
const body = m[3]
while (j < body.length) {
re.lastIndex = j
const l = re.exec(body)
if (!l || !LABEL.test(l[1])) {
errors.push(`${at}: labels do not parse`)
break
}
labels[l[1]] = l[2].replace(/\\(.)/g, (_, c) => (c === 'n' ? '\n' : c))
j = re.lastIndex
}
}
const v = m[4]
const value = v === '+Inf' ? Infinity : v === '-Inf' ? -Infinity : v === 'NaN' ? NaN : Number(v)
if (!/^[-+]?(\d+\.?\d*([eE][-+]?\d+)?|\.\d+([eE][-+]?\d+)?|Inf|NaN)$/.test(v)) errors.push(`${at}: not a value`)
family(owner(m[1])).samples.push({ name: m[1], labels, value })
}
return { families, errors }
}