Files
peardata/server/rest/formatters.js
T
Raven Scott f7e26d1aac
Release rolling / release (push) Successful in 25s
CI / test (push) Successful in 28s
Testing
2026-07-18 16:33:43 -04:00

66 lines
2.1 KiB
JavaScript

/**
* Export formatters (JSON / Prometheus / shell) for /api/v1|v2|v3/allmetrics.
*/
import os from 'os'
import { getStore } from '../services/store.js'
import { CHART_BY_ID } from '../../shared/metrics.js'
import { APP_NAME, APP_VERSION } from '../../shared/protocol.js'
/**
* @param {'json'|'prometheus'|'shell'} format
*/
export function formatAllMetrics(format = 'json') {
const latest = getStore().latestValues()
if (format === 'prometheus') return { contentType: 'text/plain; version=0.0.4', body: toPrometheus(latest) }
if (format === 'shell') return { contentType: 'text/plain', body: toShell(latest) }
return {
contentType: 'application/json',
body: {
hostname: os.hostname(),
app: APP_NAME,
version: APP_VERSION,
charts: Object.fromEntries(
Object.entries(latest).map(([chart, point]) => [
chart,
{
name: chart,
context: CHART_BY_ID.get(chart)?.context || chart,
last_updated: Math.floor(point.ts / 1000),
dimensions: point.values,
},
])
),
},
}
}
/**
* @param {Record<string, { ts: number, values: Record<string, number|null> }>} latest
*/
function toPrometheus(latest) {
const lines = [`# HELP peardata_info PearData agent info`, `# TYPE peardata_info gauge`]
lines.push(`peardata_info{version="${APP_VERSION}",hostname="${os.hostname()}"} 1`)
for (const [chart, point] of Object.entries(latest)) {
const metric = chart.replace(/\./g, '_')
for (const [dim, val] of Object.entries(point.values)) {
if (val == null || Number.isNaN(val)) continue
lines.push(`${metric}{dimension="${dim}"} ${val}`)
}
}
return lines.join('\n') + '\n'
}
/**
* @param {Record<string, { ts: number, values: Record<string, number|null> }>} latest
*/
function toShell(latest) {
const lines = []
for (const [chart, point] of Object.entries(latest)) {
for (const [dim, val] of Object.entries(point.values)) {
if (val == null || Number.isNaN(val)) continue
lines.push(`PEARDATA_${chart.replace(/\./g, '_').toUpperCase()}_${dim.toUpperCase()}="${val}"`)
}
}
return lines.join('\n') + '\n'
}