Skip to content

Commit f47a7fd

Browse files
committed
Code cleaning
* Remove WebAPI leftovers * Remove leftovers from autocompleters function signature * Refit autocompleter related types * It happened (Removed useless branch with `make it happen` comment) * Fix host tag group autocompleters * Bumped dependencies
1 parent 2e2dc95 commit f47a7fd

File tree

8 files changed

+327
-450
lines changed

8 files changed

+327
-450
lines changed

package-lock.json

Lines changed: 291 additions & 306 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/DataSource.ts

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,13 @@ import {
66
MetricFindValue,
77
TestDataSourceResponse,
88
} from '@grafana/data';
9-
import { FetchResponse } from '@grafana/runtime';
109
import { EditionFamily, getEditionFamily } from 'edition';
1110
import { replaceVariables } from 'utils';
1211

1312
import { MetricFindQuery, RequestSpec } from './RequestSpec';
1413
import RestApiBackend from './backend/rest';
1514
import { Settings } from './settings';
16-
import { CmkQuery, DataSourceOptions, Edition, ResponseDataAutocomplete, type WebApiResponse } from './types';
15+
import { AutocompleterEntry, CmkQuery, DataSourceOptions, Edition } from './types';
1716
import { AutoCompleteParams } from './ui/autocomplete';
1817
import { createCmkContext } from './utils';
1918

@@ -42,11 +41,8 @@ export class DataSource extends DataSourceApi<CmkQuery> {
4241
return this.restBackend.testDatasource();
4342
}
4443

45-
async autocompleterRequest(
46-
api_url: string,
47-
data: unknown
48-
): Promise<FetchResponse<WebApiResponse<ResponseDataAutocomplete>>> {
49-
return this.restBackend.autocompleterRequest(api_url, data);
44+
async autocompleterRequest(data: unknown): Promise<AutocompleterEntry[]> {
45+
return this.restBackend.autocompleterRequest(data);
5046
}
5147

5248
async contextAutocomplete(
@@ -57,15 +53,16 @@ export class DataSource extends DataSourceApi<CmkQuery> {
5753
): Promise<Array<{ value: string; label: string; isDisabled: boolean }>> {
5854
const context = createCmkContext(replaceVariables(partialRequestSpec));
5955

60-
const response = await this.autocompleterRequest('ajax_vs_autocomplete.py', {
56+
const response = await this.autocompleterRequest({
6157
ident,
6258
value: prefix,
6359
params: {
6460
...params,
6561
context,
6662
},
6763
});
68-
return response.data.result.choices.map(([value, label]: [string, string]) => ({
64+
65+
return response.map(([value, label]: [string, string]) => ({
6966
value,
7067
label,
7168
isDisabled: value === null,

src/api_utils.ts

Lines changed: 3 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,6 @@
11
import { GraphType, NegatableOption, RequestSpec, TagValue } from './RequestSpec';
2-
import { Context, Edition, Params } from './types';
3-
import { aggregationToPresentation, createCmkContext, presentationToAggregation } from './utils';
4-
5-
export interface WebApiCurve {
6-
title: string;
7-
rrddata: Array<{
8-
i: number;
9-
d: Record<string, unknown>;
10-
}>;
11-
}
12-
export interface WebAPiGetGraphResult {
13-
start_time: number;
14-
end_time: number;
15-
step: number;
16-
curves: WebApiCurve[];
17-
}
18-
19-
export interface WebApiResponse<Result> {
20-
result_code: number;
21-
result: Result;
22-
severity: string | undefined;
23-
}
2+
import { Context, Params } from './types';
3+
import { presentationToAggregation } from './utils';
244

255
function transform_negated(
266
context_property: Record<string, string | undefined> | undefined,
@@ -86,69 +66,7 @@ export function requestSpecFromLegacy(context: Context, params: Params): Partial
8666
}
8767

8868
rs.graph_type = graphModeToGraphType(params.graphMode);
89-
if (rs.graph_type === 'single_metric') {
90-
rs.graph = params.graph_name;
91-
} else {
92-
rs.graph = params.graph_name; // TODO: make this happen!
93-
}
69+
rs.graph = params.graph_name;
9470
rs.aggregation = presentationToAggregation(params.presentation);
9571
return rs;
9672
}
97-
98-
export function createWebApiRequestSpecification(
99-
requestSpec: Partial<RequestSpec>,
100-
edition: Edition
101-
): [string, Record<string, unknown>] {
102-
if (edition === 'RAW') {
103-
const specification: Record<string, unknown> = {};
104-
if (requestSpec.graph_type === 'single_metric') {
105-
specification.graph_id = 'METRIC_' + requestSpec.graph;
106-
} else {
107-
specification.graph_name = requestSpec.graph;
108-
}
109-
return [
110-
'template',
111-
{
112-
site: requestSpec.site,
113-
host_name: requestSpec.host_name,
114-
service_description: requestSpec.service,
115-
...specification,
116-
},
117-
];
118-
}
119-
const context = createCmkContext(requestSpec);
120-
let graph_template: string | undefined = undefined;
121-
if (requestSpec.graph && requestSpec.graph !== '') {
122-
if (requestSpec.graph_type === 'single_metric') {
123-
graph_template = 'METRIC_' + requestSpec.graph;
124-
} else {
125-
graph_template = requestSpec.graph;
126-
}
127-
}
128-
129-
if (requestSpec.aggregation === undefined) {
130-
throw new Error('web api: aggregation not defined!');
131-
}
132-
133-
return [
134-
'combined',
135-
{
136-
context: context,
137-
datasource: 'services',
138-
single_infos: ['host'],
139-
graph_template: graph_template,
140-
presentation: aggregationToPresentation(requestSpec.aggregation),
141-
},
142-
];
143-
}
144-
145-
export const buildUrlWithParams = (url: string, params: Record<string, string>): string =>
146-
url + '?' + new URLSearchParams(params).toString();
147-
export const buildRequestBody = (data: unknown): string => `request=${JSON.stringify(data)}`;
148-
149-
export function createWebApiRequestBody(context: [string, Record<string, unknown>], timeRange: number[]) {
150-
return {
151-
specification: context,
152-
data_range: { time_range: timeRange },
153-
};
154-
}

src/backend/rest.ts

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,8 @@ import { EditionFamily, getEditionFamily, isCloudEdition } from 'edition';
1717
import { lastValueFrom } from 'rxjs';
1818

1919
import { Aggregation, GraphType, MetricFindQuery } from '../RequestSpec';
20-
import { CmkQuery, ResponseDataAutocomplete } from '../types';
20+
import { AutocompleterEntry, CmkQuery } from '../types';
2121
import { createCmkContext, replaceVariables, toLiveStatusQuery, updateMetricTitles, updateQuery } from '../utils';
22-
import { type WebApiResponse } from './../types';
2322
import { Backend, DatasourceOptions } from './types';
2423
import { validateRequestSpec } from './validate';
2524

@@ -375,10 +374,7 @@ export default class RestApiBackend implements Backend {
375374
}
376375
}
377376

378-
async autocompleterRequest(
379-
api_url = '',
380-
data: unknown
381-
): Promise<FetchResponse<WebApiResponse<ResponseDataAutocomplete>>> {
377+
async autocompleterRequest(data: unknown): Promise<AutocompleterEntry[]> {
382378
const { ident, params: parameters, value } = data as { ident: string; value: unknown; params: unknown };
383379

384380
const response = await this.api<RestApiAutocompleteResponse>({
@@ -389,15 +385,6 @@ export default class RestApiBackend implements Backend {
389385

390386
const choices = response?.data?.choices || [];
391387

392-
const new_data: WebApiResponse<ResponseDataAutocomplete> = {
393-
result_code: 200,
394-
severity: 'success',
395-
result: {
396-
choices: choices.map((element) => [element.id, element.value]),
397-
},
398-
};
399-
400-
const res: FetchResponse<WebApiResponse<ResponseDataAutocomplete>> = { ...response, data: new_data };
401-
return res;
388+
return choices.map((element) => [element.id, element.value]);
402389
}
403390
}

src/types.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,9 @@ export interface DataSourceOptions extends DataSourceJsonData {
7575
export interface SecureJsonData {
7676
secret?: string;
7777
}
78-
78+
export type AutocompleterEntry = [string, string];
7979
export interface ResponseDataAutocomplete {
80-
choices: Array<[string, string]>;
80+
choices: AutocompleterEntry[];
8181
}
8282

8383
export enum LabelVariableNames {
@@ -88,9 +88,3 @@ export enum LabelVariableNames {
8888
SERVICE = '$filter_service',
8989
SERVICE_IN_GROUP = '$filter_service_in_group',
9090
}
91-
92-
export interface WebApiResponse<Result> {
93-
result_code: number;
94-
result: Result;
95-
severity: string | undefined;
96-
}

src/ui/filters.tsx

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { SelectableValue } from '@grafana/data';
12
import React from 'react';
23

34
import { DataSource } from '../DataSource';
@@ -72,22 +73,27 @@ export const Filters = (props: FiltersProp): React.JSX.Element => {
7273
[datasource, qSite]
7374
);
7475
const hostTagAutocompleter = React.useCallback(
75-
(prefix: string, mode: 'groups' | 'choices', context: Record<string, unknown>) => {
76+
async (
77+
prefix: string,
78+
mode: 'groups' | 'choices',
79+
context: Record<string, unknown>
80+
): Promise<Array<SelectableValue<string>>> => {
7681
if (mode === 'groups') {
77-
return datasource.contextAutocomplete('tag_groups', { site: qSite, ...context }, prefix, { strict: true });
82+
return await datasource.contextAutocomplete('tag_groups', { site: qSite, ...context }, prefix, {
83+
strict: true,
84+
});
7885
} else {
79-
return (async function () {
80-
// TODO: would have expected that this is dependent on the site, but does not look like that?
81-
const response = await datasource.autocompleterRequest('ajax_vs_autocomplete.py', {
82-
ident: 'tag_groups_opt',
83-
params: { group_id: context.groupId, strict: true },
84-
value: prefix,
85-
});
86-
return response.data.result.choices.map(([value, label]: [string, string]) => ({
87-
value,
88-
label,
89-
}));
90-
})();
86+
const options = await datasource.autocompleterRequest({
87+
ident: 'tag_groups_opt',
88+
params: { group_id: context.groupId, strict: true },
89+
value: prefix,
90+
});
91+
92+
return options.map(([value, label]: [string, string]) => ({
93+
value,
94+
label,
95+
isDisabled: value === null,
96+
}));
9197
}
9298
},
9399
[datasource, qSite]

src/utils.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { getTemplateSrv } from '@grafana/runtime';
33
import { isUndefined } from 'lodash';
44

55
import { Aggregation, FiltersRequestSpec, NegatableOption, RequestSpec, TagValue } from './RequestSpec';
6-
import { WebApiCurve, requestSpecFromLegacy } from './api_utils';
6+
import { requestSpecFromLegacy } from './api_utils';
77
import { MetricResponse } from './backend/rest';
88
import { CmkQuery, LabelVariableNames } from './types';
99
import { Presentation } from './ui/autocomplete';
@@ -261,7 +261,7 @@ export function toLiveStatusQuery(filter: Partial<FiltersRequestSpec>, table: 'h
261261
};
262262
}
263263

264-
type GrapResponse = WebApiCurve | MetricResponse;
264+
type GrapResponse = MetricResponse;
265265

266266
export function updateMetricTitles(metrics: GrapResponse[], query: CmkQuery, scopedVars: ScopedVars = {}) {
267267
const titleTemplate = query.requestSpec?.label || LabelVariableNames.ORIGINAL;

tests/unit/DataSource.test.ts

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,13 @@ import { cloneDeep } from 'lodash';
44

55
import { DataSource } from '../../src/DataSource';
66
import { RequestSpec } from '../../src/RequestSpec';
7-
import { buildRequestBody, buildUrlWithParams } from '../../src/api_utils';
87
import RestApiBackend from '../../src/backend/rest';
98
import { CmkQuery, DataSourceOptions, Edition } from '../../src/types';
109
import { labelForRequestSpecKey } from '../../src/ui/utils';
1110
import * as utils from '../../src/utils';
1211

1312
jest.mock('../../src/utils');
1413

15-
describe('URL conversions', () => {
16-
it('Params', () => {
17-
expect(buildUrlWithParams('hi', { A: '5', TE: 'TTI' })).toBe('hi?A=5&TE=TTI');
18-
});
19-
it('Request body', () => {
20-
expect(buildRequestBody({ spec: ['comb', { site: 'heute' }] })).toBe('request={"spec":["comb",{"site":"heute"}]}');
21-
});
22-
});
23-
2414
// from https://stackoverflow.com/questions/42773836/how-to-find-all-subsets-of-a-set-in-javascript-powerset-of-array
2515
const allSubsets = (values: string[]): string[][] =>
2616
values.reduce((subsets, value) => subsets.concat(subsets.map((set) => [value, ...set])), [[]]);

0 commit comments

Comments
 (0)