Skip to content

Commit

Permalink
Add time zone support for timeseries (#386)
Browse files Browse the repository at this point in the history
Adds time zone support for aggregated time series. The user can select the time zone using the Grafana time range options. This is especially useful when daily or monthly granularity is used.
  • Loading branch information
lpereiracgn authored Jun 18, 2024
1 parent 223fe72 commit 95e4374
Show file tree
Hide file tree
Showing 10 changed files with 40 additions and 24 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
This article documents the ongoing improvements we're making to the **Cognite
Data Source for Grafana**.

## 4.2.0 - June 17th, 2024

### Features

- Adds time zone support for aggregated time series, the user can select the timezone using the Grafana time range options.

## 4.1.3 - May 7th, 2024

### Bug fixes
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cognite/cognite-grafana-datasource",
"version": "4.1.3",
"version": "4.2.0",
"description": "Cognite Data Fusion datasource",
"repository": "https://github.com/cognitedata/cognite-grafana-datasource",
"author": "Cognite AS",
Expand Down
12 changes: 0 additions & 12 deletions src/__mocks__/@grafana/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,3 @@ export const getTemplateSrv = () =>
return query;
}),
} as any);

export const SystemJS = {
load: async (module) => {
return module === 'app/core/app_events' ? AppEvents : new Error('mo mock');
},
};

const AppEvents = {
emit: jest.fn(),
on: jest.fn(),
off: jest.fn(),
};
13 changes: 13 additions & 0 deletions src/__tests__/__snapshots__/datasource.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ exports[`Datasource Query Give "Select Timeseries of Relationships target from A
],
"limit": 10000,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
"headers": undefined,
"method": "POST",
Expand Down Expand Up @@ -188,6 +189,7 @@ exports[`Datasource Query Given "Select Timeseries from Asset" queries should ge
],
"limit": 3333,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
"headers": undefined,
"method": "POST",
Expand All @@ -211,6 +213,7 @@ exports[`Datasource Query Given "Select Timeseries from Asset" queries should ge
],
"limit": 10000,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
"headers": undefined,
"method": "POST",
Expand Down Expand Up @@ -359,6 +362,7 @@ exports[`Datasource Query Given "Select Timeseries" queries should generate the
],
"limit": 10000,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
"headers": undefined,
"method": "POST",
Expand All @@ -382,6 +386,7 @@ exports[`Datasource Query Given "Select Timeseries" queries should generate the
],
"limit": 10000,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
"headers": undefined,
"method": "POST",
Expand Down Expand Up @@ -445,6 +450,7 @@ exports[`Datasource Query Given custom queries should generate the correct filte
"expression": "ts{id=1, aggregate="discreteVariance", granularity="10d"}",
"limit": 10000,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
],
},
Expand All @@ -464,6 +470,7 @@ exports[`Datasource Query Given custom queries should generate the correct filte
"expression": "ts{externalId="Timeseries1"}",
"limit": 10000,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
],
},
Expand Down Expand Up @@ -555,18 +562,21 @@ exports[`Datasource Query Given custom queries with functions should generate th
"expression": "ts{id=1} + pi()",
"limit": 3333,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
{
"end": 1549338475000,
"expression": "ts{id=2} + pi()",
"limit": 3333,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
{
"end": 1549338475000,
"expression": "ts{id=3} + pi()",
"limit": 3333,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
],
},
Expand All @@ -586,18 +596,21 @@ exports[`Datasource Query Given custom queries with functions should generate th
"expression": "ts{id=1} * ts{externalId="Timeseries1", aggregate="average"} - ts{externalId="Timeseries1", aggregate="average", granularity="10m"}",
"limit": 3333,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
{
"end": 1549338475000,
"expression": "ts{id=2} * ts{externalId="Timeseries1", aggregate="average"} - ts{externalId="Timeseries1", aggregate="average", granularity="10m"}",
"limit": 3333,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
{
"end": 1549338475000,
"expression": "ts{id=3} * ts{externalId="Timeseries1", aggregate="average"} - ts{externalId="Timeseries1", aggregate="average", granularity="10m"}",
"limit": 3333,
"start": 1549336675000,
"timeZone": "Europe/Oslo",
},
],
},
Expand Down
2 changes: 2 additions & 0 deletions src/__tests__/datasource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const options: any = {
format: 'json',
panelId: 1,
dashboardUID: 1,
timezone: 'Europe/Oslo'
};
const tsResponseWithId = (id, externalId = `Timeseries${id}`, description = 'test timeseries') =>
getItemsResponseObject([{ id, externalId, description }]);
Expand Down Expand Up @@ -88,6 +89,7 @@ describe('Datasource Query', () => {
aggregates,
limit: 10000,
granularity: '30s',
timeZone: 'Europe/Oslo',
});
});

Expand Down
4 changes: 3 additions & 1 deletion src/__tests__/datasource.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ describe('formQueryForItems: enrich items with additional props for request', ()
const queryOptions = {
range: { from: dateTime(0), to: dateTime(3000) },
intervalMs: 2000,
} as QueryOptions;
timeZone: 'UTC',
} as any;

it('for timeseries/data request', () => {
const queryItems = formQueryForItems(
Expand All @@ -84,6 +85,7 @@ describe('formQueryForItems: enrich items with additional props for request', ()
],
limit: 10000,
start: 0,
timeZone: 'UTC'
});
});

Expand Down
16 changes: 10 additions & 6 deletions src/cdf/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { get, cloneDeep } from 'lodash';
import { DataFrame, Field, TableData, TimeSeries, guessFieldTypeFromNameAndValue } from '@grafana/data';
import { DataFrame, Field, TableData, TimeSeries, guessFieldTypeFromNameAndValue, getTimeZone } from '@grafana/data';
import {
TimeSeriesDatapoint,
Timestamp,
Expand All @@ -24,6 +24,7 @@ import {
ResponseMetadata,
Aggregates,
Granularity,
TimeZone,
Tuple,
SuccessResponse,
Responses,
Expand All @@ -45,7 +46,7 @@ const variableLabelRegex = /{{([^{}]+)}}/g;

export function formQueryForItems(
{ items, type, target }: QueriesDataItem,
{ range, intervalMs }: QueryOptions
{ range, intervalMs, timeZone }: QueryOptions & { timeZone: string }
): CDFDataQueryRequest {
const { aggregation, granularity } = target;
const [start, end] = getRange(range);
Expand All @@ -54,7 +55,7 @@ export function formQueryForItems(
case 'synthetic': {
const limit = calculateDPLimitPerQuery(items.length);
return {
items: items.map(({ expression }) => ({ expression, start, end, limit })),
items: items.map(({ expression }) => ({ expression, start, end, limit, timeZone })),
};
}
case 'latest': {
Expand All @@ -63,12 +64,13 @@ export function formQueryForItems(
};
}
default: {
let aggregations: Aggregates & Granularity = null;
let aggregations: Aggregates & Granularity & TimeZone = null;
const isAggregated = aggregation && aggregation !== 'none';
if (isAggregated) {
aggregations = {
aggregates: [aggregation],
granularity: granularity || toGranularityWithLowerBound(intervalMs),
timeZone,
};
}
const limit = calculateDPLimitPerQuery(items.length, isAggregated);
Expand All @@ -77,7 +79,7 @@ export function formQueryForItems(
end,
start,
items,
limit,
limit
};
}
}
Expand All @@ -91,7 +93,9 @@ export function formQueriesForTargets(
queriesData: QueriesDataItem[],
options: QueryOptions
): CDFDataQueryRequest[] {
return queriesData.map((itemsData) => formQueryForItems(itemsData, options));
const timeZoneValue = options.timezone === 'browser' ? Intl.DateTimeFormat().resolvedOptions().timeZone : options.timezone;
const timeZone = timeZoneValue === 'utc' ? timeZoneValue.toUpperCase() : timeZoneValue
return queriesData.map((itemsData) => formQueryForItems(itemsData, {...options, timeZone }));
}

export async function getLabelsForTarget(
Expand Down
4 changes: 1 addition & 3 deletions src/components/queryEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import defaults from 'lodash/defaults';
import React, { useState, useEffect, useCallback } from 'react';
import React, { useState, useEffect } from 'react';
import {
LegacyForms,
Tab,
Expand All @@ -14,7 +14,6 @@ import {
Input
} from '@grafana/ui';
import { SelectableValue } from '@grafana/data';
import { SystemJS } from '@grafana/runtime';
import { CustomQueryHelp } from './queryHelp';
import CogniteDatasource, { resource2DropdownOption } from '../datasource';
import {
Expand All @@ -27,7 +26,6 @@ import {
EditorProps,
SelectedProps,
OnQueryChange,
AssetQuery,
} from '../types';
import { failedResponseEvent, responseWarningEvent } from '../constants';
import { ResourceSelect } from './resourceSelect';
Expand Down
2 changes: 1 addition & 1 deletion src/datasource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
Resource,
IdEither,
} from './cdf/types';
import { Connector, Fetcher } from './connector';
import { Connector } from './connector';
import { CacheTime } from './constants';
import { parse as parseQuery } from './parser/events-assets';
import { ParsedFilter, QueryCondition } from './parser/types';
Expand Down
3 changes: 3 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,10 +416,12 @@ export type DataQueryRequestItem = {
aggregates?: string[];
id?: number;
externalId?: string;
timeZone?: string;
};

export type Aggregates = Pick<CDFDataQueryRequest, 'aggregates'>;
export type Granularity = Pick<CDFDataQueryRequest, 'granularity'>;
export type TimeZone = Pick<CDFDataQueryRequest, 'timeZone'>;

export interface CDFDataQueryRequest {
items: DataQueryRequestItem[];
Expand All @@ -428,6 +430,7 @@ export interface CDFDataQueryRequest {
limit?: number;
aggregates?: string[];
granularity?: string;
timeZone?: string;
}

export interface DataResponse<T> {
Expand Down

0 comments on commit 95e4374

Please sign in to comment.