GrafanaUI: improve Prometheus getQueryHints performance (#52148)

This commit is contained in:
timkendrickmw 2022-08-11 14:47:07 +01:00 committed by GitHub
parent c08fe3a53c
commit 85dbacafdb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -34,23 +34,28 @@ export function getQueryHints(query: string, series?: any[], datasource?: Promet
// Use metric metadata for exact types
const nameMatch = query.match(/\b(\w+_(total|sum|count))\b/);
let counterNameMetric = nameMatch ? nameMatch[1] : '';
const metricsMetadata = datasource?.languageProvider?.metricsMetadata ?? {};
const metricMetadataKeys = Object.keys(metricsMetadata);
const metricsMetadata = datasource?.languageProvider?.metricsMetadata;
let certain = false;
if (metricMetadataKeys.length > 0) {
if (metricsMetadata) {
// Tokenize the query into its identifiers (see https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels)
const queryTokens = Array.from(query.matchAll(/\$?[a-zA-Z_:][a-zA-Z0-9_:]*/g))
.map(([match]) => match)
// Exclude variable identifiers
.filter((token) => !token.startsWith('$'))
// Split composite keys to match the tokens returned by the language provider
.flatMap((token) => token.split(':'));
// Determine whether any of the query identifier tokens refers to a counter metric
counterNameMetric =
metricMetadataKeys.find((metricName) => {
queryTokens.find((metricName) => {
// Only considering first type information, could be non-deterministic
const metadata = metricsMetadata[metricName];
if (metadata.type.toLowerCase() === 'counter') {
const metricRegex = new RegExp(`\\b${metricName}\\b`);
if (query.match(metricRegex)) {
if (metadata && metadata.type.toLowerCase() === 'counter') {
certain = true;
return true;
}
}
} else {
return false;
}
}) ?? '';
}