Loki: Fix error when empty template variables response (#69373)

* Loki: Fix error when empty template variables

* Update

* Add test

* Add test for statsMetadataRequest
This commit is contained in:
Ivana Huckova 2023-06-05 15:16:12 +02:00 committed by GitHub
parent 97221595c1
commit 3150d80428
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 3 deletions

View File

@ -32,7 +32,7 @@ import { LokiDatasource, REF_ID_DATA_SAMPLES } from './datasource';
import { createLokiDatasource, createMetadataRequest } from './mocks';
import { runSplitQuery } from './querySplitting';
import { parseToNodeNamesArray } from './queryUtils';
import { LokiOptions, LokiQuery, LokiQueryType, LokiVariableQueryType, SupportingQueryType } from './types';
import { LokiOptions, LokiQuery, LokiQueryType, LokiVariableQueryType, QueryStats, SupportingQueryType } from './types';
import { LokiVariableSupport } from './variables';
jest.mock('@grafana/runtime', () => {
@ -1139,6 +1139,24 @@ describe('LokiDatasource', () => {
});
});
});
describe('getQueryStats', () => {
it('uses statsMetadataRequest', async () => {
const ds = createLokiDatasource(templateSrvStub);
const spy = jest.spyOn(ds, 'statsMetadataRequest').mockResolvedValue({} as QueryStats);
ds.getQueryStats('{foo="bar"}');
expect(spy).toHaveBeenCalled();
});
});
describe('statsMetadataRequest', () => {
it('throws error if url starts with /', () => {
const ds = createLokiDatasource();
expect(async () => {
await ds.statsMetadataRequest('/index');
}).rejects.toThrow('invalid metadata request url: /index');
});
});
});
describe('applyTemplateVariables', () => {

View File

@ -422,7 +422,21 @@ export class LokiDatasource
}
const res = await this.getResource(url, params, options);
return res.data ?? (res || []);
return res.data || [];
}
// We need a specific metadata method for stats endpoint as it does not return res.data,
// but it returns stats directly in res object.
async statsMetadataRequest(
url: string,
params?: Record<string, string | number>,
options?: Partial<BackendSrvRequest>
): Promise<QueryStats> {
if (url.startsWith('/')) {
throw new Error(`invalid metadata request url: ${url}`);
}
return await this.getResource(url, params, options);
}
async getQueryStats(query: string): Promise<QueryStats | undefined> {
@ -438,7 +452,7 @@ export class LokiDatasource
for (const labelMatcher of labelMatchers) {
try {
const data = await this.metadataRequest(
const data = await this.statsMetadataRequest(
'index/stats',
{ query: labelMatcher, start, end },
{ showErrorAlert: false }