grafana/public/app/core/utils/explore.ts

352 lines
12 KiB
TypeScript
Raw Normal View History

import { customAlphabet } from 'nanoid';
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 10:28:46 -05:00
import { Unsubscribable } from 'rxjs';
import { v4 as uuidv4 } from 'uuid';
import {
AdHocVariableFilter,
CoreApp,
DataQuery,
DataQueryRequest,
DataSourceApi,
DataSourceRef,
DefaultTimeZone,
HistoryItem,
IntervalValues,
LogsDedupStrategy,
LogsSortOrder,
rangeUtil,
RawTimeRange,
ScopedVars,
TimeRange,
TimeZone,
toURLRange,
urlUtil,
} from '@grafana/data';
import { getDataSourceSrv } from '@grafana/runtime';
import { RefreshPicker } from '@grafana/ui';
import store from 'app/core/store';
import { ExpressionDatasourceUID } from 'app/features/expressions/types';
import { QueryOptions, QueryTransaction } from 'app/types/explore';
import { getNextRefIdChar } from './query';
2018-10-01 05:56:26 -05:00
2019-01-31 12:38:49 -06:00
export const DEFAULT_UI_STATE = {
2019-02-07 10:46:33 -06:00
dedupStrategy: LogsDedupStrategy.none,
2019-01-31 12:38:49 -06:00
};
export const ID_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
const nanoid = customAlphabet(ID_ALPHABET, 3);
const MAX_HISTORY_ITEMS = 100;
const LAST_USED_DATASOURCE_KEY = 'grafana.explore.datasource';
const lastUsedDatasourceKeyForOrgId = (orgId: number) => `${LAST_USED_DATASOURCE_KEY}.${orgId}`;
export const getLastUsedDatasourceUID = (orgId: number) =>
store.getObject<string>(lastUsedDatasourceKeyForOrgId(orgId));
export const setLastUsedDatasourceUID = (orgId: number, datasourceUID: string) =>
store.setObject(lastUsedDatasourceKeyForOrgId(orgId), datasourceUID);
2019-01-10 07:24:31 -06:00
export interface GetExploreUrlArguments {
queries: DataQuery[];
dsRef: DataSourceRef | null | undefined;
timeRange: TimeRange;
scopedVars: ScopedVars | undefined;
adhocFilters?: AdHocVariableFilter[];
}
export function generateExploreId() {
while (true) {
const id = nanoid(3);
if (!/^\d+$/.test(id)) {
return id;
}
}
}
/**
* Returns an Explore-URL that contains a panel's queries and the dashboard time range.
*/
export async function getExploreUrl(args: GetExploreUrlArguments): Promise<string | undefined> {
const { queries, dsRef, timeRange, scopedVars, adhocFilters } = args;
const interpolatedQueries = (
await Promise.allSettled(
queries
// Explore does not support expressions so filter those out
.filter((q) => q.datasource?.uid !== ExpressionDatasourceUID)
.map(async (q) => {
// if the query defines a datasource, use that one, otherwise use the one from the panel, which should always be defined.
// this will rejects if the datasource is not found, or return the default one if dsRef is not provided.
const queryDs = await getDataSourceSrv().get(q.datasource || dsRef);
return {
// interpolate the query using its datasource `interpolateVariablesInQueries` method if defined, othewise return the query as-is.
...(queryDs.interpolateVariablesInQueries?.([q], scopedVars ?? {}, adhocFilters)[0] || q),
// But always set the datasource as it's required in Explore.
// NOTE: if for some reason the query has the "mixed" datasource, we omit the property;
// Upon initialization, Explore use its own logic to determine the datasource.
...(!queryDs.meta.mixed && { datasource: queryDs.getRef() }),
};
})
)
)
.filter(
<T>(promise: PromiseSettledResult<T>): promise is PromiseFulfilledResult<T> => promise.status === 'fulfilled'
)
.map((q) => q.value);
const exploreState = JSON.stringify({
[generateExploreId()]: { range: toURLRange(timeRange.raw), queries: interpolatedQueries, datasource: dsRef?.uid },
});
return urlUtil.renderUrl('/explore', { panes: exploreState, schemaVersion: 1 });
}
2018-10-01 05:56:26 -05:00
export function requestIdGenerator(exploreId: string) {
return `explore_${exploreId}`;
}
2019-01-10 07:24:31 -06:00
export function buildQueryTransaction(
exploreId: string,
queries: DataQuery[],
2019-01-10 07:24:31 -06:00
queryOptions: QueryOptions,
range: TimeRange,
DateTime: adding support to select preferred timezone for presentation of date and time values. (#23586) * added moment timezone package. * added a qnd way of selecting timezone. * added a first draft to display how it can be used. * fixed failing tests. * made moment.local to be in utc when running tests. * added tests to verify that the timeZone support works as expected. * Fixed so we use the formatter in the graph context menu. * changed so we will format d3 according to timeZone. * changed from class base to function based for easier consumption. * fixed so tests got green. * renamed to make it shorter. * fixed formatting in logRow. * removed unused value. * added time formatter to flot. * fixed failing tests. * changed so history will use the formatting with support for timezone. * added todo. * added so we append the correct abbrivation behind time. * added time zone abbrevation in timepicker. * adding timezone in rangeutil tool. * will use timezone when formatting range. * changed so we use new functions to format date so timezone is respected. * wip - dashboard settings. * changed so the time picker settings is in react. * added force update. * wip to get the react graph to work. * fixed formatting and parsing on the timepicker. * updated snap to be correct. * fixed so we format values properly in time picker. * make sure we pass timezone on all the proper places. * fixed so we use correct timeZone in explore. * fixed failing tests. * fixed so we always parse from local to selected timezone. * removed unused variable. * reverted back. * trying to fix issue with directive. * fixed issue. * fixed strict null errors. * fixed so we still can select default. * make sure we reads the time zone from getTimezone
2020-04-27 08:28:06 -05:00
scanning: boolean,
Correlations: Add an editor in Explore (#73315) * Start adding correlations editor mode * Add selector for merge conflict resolution * Enable saving * Build out new corelation helper component * flesh out save with label/description, change color * Have breadcrumb exit correlation editor mode * Add extension property to show/hide, use it for correlations * Bring in feature toggle * Remove unnecessary param * Cleanup * Parse logs json * Work on correlation edit mode bar * Tinker with a top element for the editor mode * Handle various explore state changes with correlations editor mode * WIP - add unsaved changes modal * Have correlation bar always rendered, sometimes hidden * Add various prompt modals * Clear correlations data on mode bar unmount, only use not left pane changes to count as dirty * Move special logic to explore * Remove all shouldShow logic from plugin extensions * remove grafana data changes * WIP - clean up correlations state * Interpolate data before sending to onclick * Override outline button coloring to account for dark background * More cleanup, more color tweaking * Prettier formatting, change state to refer to editor * Fix tests * More state change tweaks * ensure correlation save ability, change correlation editor state vars * fix import * Remove independent selector for editorMode, work close pane into editor exit flow * Add change datasource post action * Clean up based on PR feedback, handle closing left panel with helper better * Remove breadcrumb additions, add section and better ID to cmd palette action * Interpolate query results if it is ran with a helper with vars * Pass the datasource query along with the correlate link to ensure the datasource unique ID requirement passes * Use different onmount function to capture state of panes at time of close instead of time of mount * Fix node graph’s datalink not working * Actually commit the fix to saving * Fix saving correlations with mixed datasource to use the first query correlation UID * Add tracking * Use query datasources in mixed scenario, move exit tracking to click handler * Add correlations to a place where both can be used in the correlations editor * Be more selective on when we await the datasource get * Fix CSS to use objects * Update betterer * Add test around new decorator functionality * Add tests for decorate with correlations * Some reorganization and a few tweaks based on feedback * Move dirty state change to state function and out of component * Change the verbiage around a little * Various suggestions from Gio Co-authored-by: Giordano Ricci <me@giordanoricci.com> * More small Gio-related tweaks * Tie helper data to datasource - clear it out when the datasource changes * Missed another Gio tweak * Fix linter error * Only clear helper data on left pane changes * Add height offset for correlation editor bar so it doesn’t scroll off page --------- Co-authored-by: Piotr Jamróz <pm.jamroz@gmail.com> Co-authored-by: Giordano Ricci <me@giordanoricci.com>
2023-10-03 09:28:29 -05:00
timeZone?: TimeZone,
scopedVars?: ScopedVars
2019-01-10 07:24:31 -06:00
): QueryTransaction {
const panelId = Number.parseInt(exploreId, 36);
const { interval, intervalMs } = getIntervals(range, queryOptions.minInterval, queryOptions.maxDataPoints);
const request: DataQueryRequest = {
app: CoreApp.Explore,
// TODO probably should be taken from preferences but does not seem to be used anyway.
DateTime: adding support to select preferred timezone for presentation of date and time values. (#23586) * added moment timezone package. * added a qnd way of selecting timezone. * added a first draft to display how it can be used. * fixed failing tests. * made moment.local to be in utc when running tests. * added tests to verify that the timeZone support works as expected. * Fixed so we use the formatter in the graph context menu. * changed so we will format d3 according to timeZone. * changed from class base to function based for easier consumption. * fixed so tests got green. * renamed to make it shorter. * fixed formatting in logRow. * removed unused value. * added time formatter to flot. * fixed failing tests. * changed so history will use the formatting with support for timezone. * added todo. * added so we append the correct abbrivation behind time. * added time zone abbrevation in timepicker. * adding timezone in rangeutil tool. * will use timezone when formatting range. * changed so we use new functions to format date so timezone is respected. * wip - dashboard settings. * changed so the time picker settings is in react. * added force update. * wip to get the react graph to work. * fixed formatting and parsing on the timepicker. * updated snap to be correct. * fixed so we format values properly in time picker. * make sure we pass timezone on all the proper places. * fixed so we use correct timeZone in explore. * fixed failing tests. * fixed so we always parse from local to selected timezone. * removed unused variable. * reverted back. * trying to fix issue with directive. * fixed issue. * fixed strict null errors. * fixed so we still can select default. * make sure we reads the time zone from getTimezone
2020-04-27 08:28:06 -05:00
timezone: timeZone || DefaultTimeZone,
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 10:28:46 -05:00
startTime: Date.now(),
2019-01-10 07:24:31 -06:00
interval,
intervalMs,
panelId,
targets: queries, // Datasources rely on DataQueries being passed under the targets key.
range,
requestId: requestIdGenerator(exploreId),
rangeRaw: range.raw,
2019-01-10 07:24:31 -06:00
scopedVars: {
__interval: { text: interval, value: interval },
__interval_ms: { text: intervalMs, value: intervalMs },
Correlations: Add an editor in Explore (#73315) * Start adding correlations editor mode * Add selector for merge conflict resolution * Enable saving * Build out new corelation helper component * flesh out save with label/description, change color * Have breadcrumb exit correlation editor mode * Add extension property to show/hide, use it for correlations * Bring in feature toggle * Remove unnecessary param * Cleanup * Parse logs json * Work on correlation edit mode bar * Tinker with a top element for the editor mode * Handle various explore state changes with correlations editor mode * WIP - add unsaved changes modal * Have correlation bar always rendered, sometimes hidden * Add various prompt modals * Clear correlations data on mode bar unmount, only use not left pane changes to count as dirty * Move special logic to explore * Remove all shouldShow logic from plugin extensions * remove grafana data changes * WIP - clean up correlations state * Interpolate data before sending to onclick * Override outline button coloring to account for dark background * More cleanup, more color tweaking * Prettier formatting, change state to refer to editor * Fix tests * More state change tweaks * ensure correlation save ability, change correlation editor state vars * fix import * Remove independent selector for editorMode, work close pane into editor exit flow * Add change datasource post action * Clean up based on PR feedback, handle closing left panel with helper better * Remove breadcrumb additions, add section and better ID to cmd palette action * Interpolate query results if it is ran with a helper with vars * Pass the datasource query along with the correlate link to ensure the datasource unique ID requirement passes * Use different onmount function to capture state of panes at time of close instead of time of mount * Fix node graph’s datalink not working * Actually commit the fix to saving * Fix saving correlations with mixed datasource to use the first query correlation UID * Add tracking * Use query datasources in mixed scenario, move exit tracking to click handler * Add correlations to a place where both can be used in the correlations editor * Be more selective on when we await the datasource get * Fix CSS to use objects * Update betterer * Add test around new decorator functionality * Add tests for decorate with correlations * Some reorganization and a few tweaks based on feedback * Move dirty state change to state function and out of component * Change the verbiage around a little * Various suggestions from Gio Co-authored-by: Giordano Ricci <me@giordanoricci.com> * More small Gio-related tweaks * Tie helper data to datasource - clear it out when the datasource changes * Missed another Gio tweak * Fix linter error * Only clear helper data on left pane changes * Add height offset for correlation editor bar so it doesn’t scroll off page --------- Co-authored-by: Piotr Jamróz <pm.jamroz@gmail.com> Co-authored-by: Giordano Ricci <me@giordanoricci.com>
2023-10-03 09:28:29 -05:00
...scopedVars,
2019-01-10 07:24:31 -06:00
},
maxDataPoints: queryOptions.maxDataPoints,
liveStreaming: queryOptions.liveStreaming,
2019-01-10 07:24:31 -06:00
};
return {
queries,
request,
2019-01-10 07:24:31 -06:00
scanning,
id: generateKey(), // reusing for unique ID
done: false,
};
}
export const clearQueryKeys: (query: DataQuery) => DataQuery = ({ key, ...rest }) => rest;
2018-11-22 04:02:53 -06:00
export const safeStringifyValue = (value: unknown, space?: number) => {
if (value === undefined || value === null) {
return '';
}
try {
return JSON.stringify(value, null, space);
} catch (error) {
console.error(error);
}
return '';
};
export function generateKey(index = 0): string {
return `Q-${uuidv4()}-${index}`;
}
export async function generateEmptyQuery(
queries: DataQuery[],
index = 0,
dataSourceOverride?: DataSourceRef
): Promise<DataQuery> {
let datasourceInstance: DataSourceApi | undefined;
let datasourceRef: DataSourceRef | null | undefined;
let defaultQuery: Partial<DataQuery> | undefined;
// datasource override is if we have switched datasources with no carry-over - we want to create a new query with a datasource we define
// it's also used if there's a root datasource and there were no previous queries
if (dataSourceOverride) {
datasourceRef = dataSourceOverride;
} else if (queries.length > 0 && queries[queries.length - 1].datasource) {
// otherwise use last queries' datasource
datasourceRef = queries[queries.length - 1].datasource;
} else {
datasourceInstance = await getDataSourceSrv().get();
defaultQuery = datasourceInstance.getDefaultQuery?.(CoreApp.Explore);
datasourceRef = datasourceInstance.getRef();
}
if (!datasourceInstance) {
datasourceInstance = await getDataSourceSrv().get(datasourceRef);
defaultQuery = datasourceInstance.getDefaultQuery?.(CoreApp.Explore);
}
return { ...defaultQuery, refId: getNextRefIdChar(queries), key: generateKey(index), datasource: datasourceRef };
}
export const generateNewKeyAndAddRefIdIfMissing = (target: DataQuery, queries: DataQuery[], index = 0): DataQuery => {
const key = generateKey(index);
const refId = target.refId || getNextRefIdChar(queries);
return { ...target, refId, key };
};
/**
* Ensure at least one target exists and that targets have the necessary keys
*
* This will return an empty array if there are no datasources, as Explore is not usable in that state
*/
export async function ensureQueries(
queries?: DataQuery[],
newQueryDataSourceOverride?: DataSourceRef
): Promise<DataQuery[]> {
2018-11-21 09:28:30 -06:00
if (queries && typeof queries === 'object' && queries.length > 0) {
const allQueries = [];
for (let index = 0; index < queries.length; index++) {
const query = queries[index];
const key = generateKey(index);
let refId = query.refId;
if (!refId) {
refId = getNextRefIdChar(allQueries);
}
// if a query has a datasource, validate it and only add it if valid
// if a query doesn't have a datasource, do not worry about it at this step
let validDS = true;
if (query.datasource) {
try {
await getDataSourceSrv().get(query.datasource.uid);
} catch {
console.error(`One of the queries has a datasource that is no longer available and was removed.`);
validDS = false;
}
}
if (validDS) {
allQueries.push({
...query,
refId,
key,
});
}
}
return allQueries;
}
try {
// if a datasource override get its ref, otherwise get the default datasource
const emptyQueryRef = newQueryDataSourceOverride ?? (await getDataSourceSrv().get()).getRef();
const emptyQuery = await generateEmptyQuery(queries ?? [], undefined, emptyQueryRef);
return [emptyQuery];
} catch {
// if there are no datasources, return an empty array because we will not allow use of explore
// this will occur on init of explore with no datasources defined
return [];
}
}
/**
* A target is non-empty when it has keys (with non-empty values) other than refId, key, context and datasource.
* FIXME: While this is reasonable for practical use cases, a query without any propery might still be "non-empty"
* in its own scope, for instance when there's no user input needed. This might be the case for an hypothetic datasource in
* which query options are only set in its config and the query object itself, as generated from its query editor it's always "empty"
*/
const validKeys = ['refId', 'key', 'context', 'datasource'];
export function hasNonEmptyQuery<TQuery extends DataQuery>(queries: TQuery[]): boolean {
2019-01-11 11:26:56 -06:00
return (
queries &&
queries.some((query) => {
const entries = Object.entries(query)
.filter(([key, _]) => validKeys.indexOf(key) === -1)
.filter(([_, value]) => value);
return entries.length > 0;
})
);
}
/**
* Update the query history. Side-effect: store history in local storage
*/
export function updateHistory<T extends DataQuery>(
history: Array<HistoryItem<T>>,
datasourceId: string,
queries: T[]
): Array<HistoryItem<T>> {
const ts = Date.now();
let updatedHistory = history;
queries.forEach((query) => {
updatedHistory = [{ query, ts }, ...updatedHistory];
});
if (updatedHistory.length > MAX_HISTORY_ITEMS) {
updatedHistory = updatedHistory.slice(0, MAX_HISTORY_ITEMS);
}
// Combine all queries of a datasource type into one history
const historyKey = `grafana.explore.history.${datasourceId}`;
try {
store.setObject(historyKey, updatedHistory);
return updatedHistory;
} catch (error) {
console.error(error);
return history;
}
}
2018-11-22 04:02:53 -06:00
export const getQueryKeys = (queries: DataQuery[]): string[] => {
const queryKeys = queries.reduce<string[]>((newQueryKeys, query, index) => {
const primaryKey = query.datasource?.uid || query.key;
2019-02-04 06:41:29 -06:00
return newQueryKeys.concat(`${primaryKey}-${index}`);
}, []);
return queryKeys;
};
export const getTimeRange = (timeZone: TimeZone, rawRange: RawTimeRange, fiscalYearStartMonth: number): TimeRange => {
let range = rangeUtil.convertRawToRange(rawRange, timeZone, fiscalYearStartMonth);
return range;
};
export const refreshIntervalToSortOrder = (refreshInterval?: string) =>
RefreshPicker.isLive(refreshInterval) ? LogsSortOrder.Ascending : LogsSortOrder.Descending;
export const stopQueryState = (querySubscription: Unsubscribable | undefined) => {
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 10:28:46 -05:00
if (querySubscription) {
querySubscription.unsubscribe();
}
};
export function getIntervals(range: TimeRange, lowLimit?: string, resolution?: number): IntervalValues {
if (!resolution) {
return { interval: '1s', intervalMs: 1000 };
}
return rangeUtil.calculateInterval(range, resolution, lowLimit);
}
export const copyStringToClipboard = (string: string) => {
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(string);
} else {
const el = document.createElement('textarea');
el.value = string;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
};