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

feat(tag): tag current value queries #16

Merged
merged 5 commits into from
Aug 14, 2023
Merged
Show file tree
Hide file tree
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
20 changes: 20 additions & 0 deletions src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,23 @@ export function enumToOptions<T>(stringEnum: { [name: string]: T }): Array<Selec

return RESULT;
}

/**
* Throws an error when called
* @param error either error object or a string
*/
export function Throw(error: string | Error): never {
if (typeof error === 'string') {
throw new Error(error);
}
throw error;
};

/**
* Throw exception if value is null or undefined
* @param value value to be checked for null or undefined
* @param error either error object or a string
*/
export function throwIfNullish<T>(value: T, error: string | Error): NonNullable<T> {
return value === undefined || value === null ? Throw(error) : value!;
}
62 changes: 61 additions & 1 deletion src/datasources/tag/TagDataSource.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { MockProxy } from 'jest-mock-extended';
import { TagDataSource } from './TagDataSource';
import { createDataSource, createFetchError } from 'test/fixtures';
import { createQueryRequest, createDataSource, createFetchError } from 'test/fixtures';
import { BackendSrv } from '@grafana/runtime';
import { TagsWithValues } from './types';

let ds: TagDataSource, backendSrv: MockProxy<BackendSrv>;

Expand All @@ -24,3 +25,62 @@ describe('testDatasource', () => {
await expect(ds.testDatasource()).rejects.toHaveProperty('status', 400);
});
});

describe('queries', () => {
test('tag current value', async () => {
backendSrv.post
.calledWith('/nitag/v2/query-tags-with-values', expect.objectContaining({ filter: 'path = "my.tag"' }))
.mockResolvedValue(createQueryTagsResponse('my.tag', '3.14'));

const result = await ds.query(createQueryRequest({ path: 'my.tag' }));

expect(result.data).toEqual([
{
fields: [{ name: 'value', values: ['3.14'] }],
name: 'my.tag',
refId: 'A',
},
]);
});

test('uses displayName property', async () => {
backendSrv.post.mockResolvedValue(createQueryTagsResponse('my.tag', '3.14', 'My cool tag'));

const result = await ds.query(createQueryRequest({ path: 'my.tag' }));

expect(result.data[0]).toEqual(expect.objectContaining({ name: 'My cool tag' }));
});

test('multiple targets - skips invalid queries', async () => {
backendSrv.post
.mockResolvedValueOnce(createQueryTagsResponse('my.tag1', '3.14'))
.mockResolvedValueOnce(createQueryTagsResponse('my.tag2', 'foo'));

const result = await ds.query(createQueryRequest({ path: 'my.tag1' }, { path: '' }, { path: 'my.tag2' }));

expect(backendSrv.post.mock.calls[0][1]).toHaveProperty('filter', 'path = "my.tag1"');
expect(backendSrv.post.mock.calls[1][1]).toHaveProperty('filter', 'path = "my.tag2"');
expect(result.data).toEqual([
{
fields: [{ name: 'value', values: ['3.14'] }],
name: 'my.tag1',
refId: 'A',
},
{
fields: [{ name: 'value', values: ['foo'] }],
name: 'my.tag2',
refId: 'C',
},
]);
});

test('throw when no tags matched', async () => {
backendSrv.post.mockResolvedValue({ tagsWithValues: [] });

await expect(ds.query(createQueryRequest({ path: 'my.tag' }))).rejects.toThrow('my.tag');
});
});

function createQueryTagsResponse(path: string, value: string, displayName?: string): TagsWithValues {
return { tagsWithValues: [{ current: { value: { value } }, tag: { path, properties: { displayName } } }] };
}
46 changes: 28 additions & 18 deletions src/datasources/tag/TagDataSource.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import {
DataFrameDTO,
DataQueryRequest,
DataQueryResponse,
DataSourceApi,
DataSourceInstanceSettings,
MutableDataFrame,
FieldType
} from '@grafana/data';

import { BackendSrv, TestingStatus, getBackendSrv } from '@grafana/runtime';

import { TagQuery } from './types';
import { TagQuery, TagsWithValues } from './types';
import { throwIfNullish } from 'core/utils';

export class TagDataSource extends DataSourceApi<TagQuery> {
baseUrl: string;
Expand All @@ -22,27 +22,37 @@ export class TagDataSource extends DataSourceApi<TagQuery> {
}

async query(options: DataQueryRequest<TagQuery>): Promise<DataQueryResponse> {
const { range } = options;
const from = range!.from.valueOf();
const to = range!.to.valueOf();

// Return a constant for each query.
const data = options.targets.map((target) => {
return new MutableDataFrame({
refId: target.refId,
fields: [
{ name: 'Time', values: [from, to], type: FieldType.time },
{ name: 'Value', values: [2.72, 3.14], type: FieldType.number },
],
});
return { data: await Promise.all(options.targets.filter(this.shouldRunQuery).map(this.runQuery, this)) };
}

private async runQuery(query: TagQuery): Promise<DataFrameDTO> {
const { tag, current } = await this.getLastUpdatedTag(query.path);

return {
refId: query.refId,
name: tag.properties.displayName ?? tag.path,
fields: [{ name: 'value', values: [current.value.value] }],
};
}

private async getLastUpdatedTag(path: string) {
const response = await this.backendSrv.post<TagsWithValues>(this.baseUrl + '/query-tags-with-values', {
filter: `path = "${path}"`,
take: 1,
orderBy: 'TIMESTAMP',
descending: true,
});

return { data };
return throwIfNullish(response.tagsWithValues[0], `No tags matched the path '${path}'`);
}

private shouldRunQuery(query: TagQuery): boolean {
return Boolean(query.path);
}

getDefaultQuery(): Omit<TagQuery, 'refId'> {
return {
path: ''
path: '',
};
}

Expand Down
14 changes: 13 additions & 1 deletion src/datasources/tag/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import { DataQuery } from '@grafana/schema'
import { DataQuery } from '@grafana/schema';

export interface TagQuery extends DataQuery {
path: string;
}

export interface TagWithValue {
current: { value: { value: string } };
tag: {
path: string;
properties: { displayName?: string };
};
}

export interface TagsWithValues {
tagsWithValues: TagWithValue[];
}
18 changes: 17 additions & 1 deletion src/test/fixtures.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DataSourceApi, DataSourceInstanceSettings, QueryEditorProps } from '@grafana/data';
import { DataQueryRequest, DataSourceApi, DataSourceInstanceSettings, QueryEditorProps, dateTime } from '@grafana/data';
import { DataQuery } from '@grafana/schema';
import { BackendSrv, FetchError } from '@grafana/runtime';
import { mock } from 'jest-mock-extended';
Expand Down Expand Up @@ -42,3 +42,19 @@ export function renderQueryEditor<DSType extends DataSourceApi<TQuery>, TQuery e
export function createFetchError(status: number): FetchError {
return mock<FetchError>({ status });
}

export function createQueryRequest<TQuery extends DataQuery>(
...targets: Array<Omit<TQuery, 'refId'>>
): DataQueryRequest<TQuery> {
return {
targets: targets.map((t, ix) => ({...t, refId: 'ABCDE'[ix]} as TQuery)),
requestId: '',
interval: '',
intervalMs: 0,
range: { from: dateTime().subtract(1, 'h'), to: dateTime(), raw: { from: 'now-6h', to: 'now' } },
scopedVars: {},
timezone: 'browser',
app: 'panel-editor',
startTime: 0,
};
}