Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: improve getMetricAsString for long strings + less allocations #587

Open
wants to merge 4 commits into
base: next
Choose a base branch
from
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions lib/registry.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

const { getValueAsString } = require('./util');

function REPLACE_FUNC(dict) {
return char => dict[char] || '';
}

class Registry {
static get PROMETHEUS_CONTENT_TYPE() {
return 'text/plain; version=0.0.4; charset=utf-8';
Expand All @@ -11,6 +15,23 @@ class Registry {
return 'application/openmetrics-text; version=1.0.0; charset=utf-8';
}

static get ESCAPE_STRING_REPLACE_MAP() {
lassic marked this conversation as resolved.
Show resolved Hide resolved
return {
'\\': '\\\\',
'\n': '\\n',
};
}

static get ESCAPE_LABEL_VALUE_REPLACE_MAP() {
return Object.assign({}, Registry.ESCAPE_STRING_REPLACE_MAP, {
lassic marked this conversation as resolved.
Show resolved Hide resolved
'"': '\\\\"',
});
}

static get ESCAPE_REPLACE_REGEXP() {
return /\\|\n|"/g;
}

constructor(regContentType = Registry.PROMETHEUS_CONTENT_TYPE) {
this._metrics = {};
this._collectors = [];
Expand Down Expand Up @@ -234,10 +255,15 @@ function escapeLabelValue(str) {
if (typeof str !== 'string') {
return str;
}
return escapeString(str).replace(/"/g, '\\"');

return escapeString(str, Registry.ESCAPE_LABEL_VALUE_REPLACE_MAP);
}
function escapeString(str) {
return str.replace(/\\/g, '\\\\').replace(/\n/g, '\\n');
function escapeString(str, extraReplaceDict) {
const fullDict = extraReplaceDict
? extraReplaceDict
: Registry.ESCAPE_STRING_REPLACE_MAP;

return str.replace(Registry.ESCAPE_REPLACE_REGEXP, REPLACE_FUNC(fullDict));
}
function standardizeCounterName(name) {
return name.replace(/_total$/, '');
Expand Down
Loading