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 all 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
27 changes: 24 additions & 3 deletions lib/registry.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@

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

const ESCAPE_STRING_REPLACE_MAP = {
'\\': '\\\\',
'\n': '\\n',
};

const ESCAPE_LABEL_VALUE_REPLACE_MAP = {
...ESCAPE_STRING_REPLACE_MAP,
'"': '\\\\"',
};

const ESCAPE_REPLACE_REGEXP = /\\|\n|"/g;

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 Down Expand Up @@ -234,10 +250,15 @@ function escapeLabelValue(str) {
if (typeof str !== 'string') {
return str;
}
return escapeString(str).replace(/"/g, '\\"');

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

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