SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat: Metrics Query Builder (#1166)
Pranshu Chittora9d3fc493a381
diff --git a/frontend/src/api/metrics/getMetricName.ts b/frontend/src/api/metrics/getMetricName.tsnew file mode 100644index 0000000000..f3bff5a921--- /dev/null+++ b/frontend/src/api/metrics/getMetricName.ts@@ -0,0 +1,27 @@+import { ApiV2Instance as axios } from 'api';+import { ErrorResponseHandler } from 'api/ErrorResponseHandler';+import { AxiosError } from 'axios';+import { ErrorResponse, SuccessResponse } from 'types/api';+import {+ MetricNameProps,+ MetricNamesPayloadProps,+} from 'types/api/metrics/getMetricName';++export const getMetricName = async (+ props: MetricNameProps,+): Promise<SuccessResponse<MetricNamesPayloadProps> | ErrorResponse> => {+ try {+ const response = await axios.get(+ `/metrics/autocomplete/list?match=${props || ''}`,+ );++ return {+ statusCode: 200,+ error: null,+ message: response.data.status,+ payload: response.data,+ };+ } catch (error) {+ return ErrorResponseHandler(error as AxiosError);+ }+};diff --git a/frontend/src/api/metrics/getQueryRange.ts b/frontend/src/api/metrics/getQueryRange.tsnew file mode 100644index 0000000000..b6715f85e6--- /dev/null+++ b/frontend/src/api/metrics/getQueryRange.ts@@ -0,0 +1,25 @@+import { ApiV2Instance as axios } from 'api';+import { ErrorResponseHandler } from 'api/ErrorResponseHandler';+import { AxiosError } from 'axios';+import { ErrorResponse, SuccessResponse } from 'types/api';+import {+ MetricRangePayloadProps,+ MetricsRangeProps,+} from 'types/api/metrics/getQueryRange';++export const getMetricsQueryRange = async (+ props: MetricsRangeProps,+): Promise<SuccessResponse<MetricRangePayloadProps> | ErrorResponse> => {+ try {+ const response = await axios.post(`/metrics/query_range`, props);++ return {+ statusCode: 200,+ error: null,+ message: response.data.status,+ payload: response.data,+ };+ } catch (error) {+ return ErrorResponseHandler(error as AxiosError);+ }+};diff --git a/frontend/src/api/metrics/getResourceAttributes.ts b/frontend/src/api/metrics/getResourceAttributes.tsindex 5be45af6f1..66524bf8f7 100644--- a/frontend/src/api/metrics/getResourceAttributes.ts+++ b/frontend/src/api/metrics/getResourceAttributes.ts@@ -3,17 +3,20 @@ import { ErrorResponseHandler } from 'api/ErrorResponseHandler';import { AxiosError } from 'axios';import { ErrorResponse, SuccessResponse } from 'types/api';import {+ TagKeyProps,TagKeysPayloadProps,TagValueProps,TagValuesPayloadProps,} from 'types/api/metrics/getResourceAttributes';-export const getResourceAttributesTagKeys = async (): Promise<- SuccessResponse<TagKeysPayloadProps> | ErrorResponse-> => {+export const getResourceAttributesTagKeys = async (+ props: TagKeyProps,+): Promise<SuccessResponse<TagKeysPayloadProps> | ErrorResponse> => {try {const response = await axios.get(- '/metrics/autocomplete/tagKey?metricName=signoz_calls_total&match=resource_',+ `/metrics/autocomplete/tagKey?metricName=${props.metricName}${+ props.match ? `&match=${props.match}` : ''+ }`,);return {@@ -32,7 +35,7 @@ export const getResourceAttributesTagValues = async (): Promise<SuccessResponse<TagValuesPayloadProps> | ErrorResponse> => {try {const response = await axios.get(- `/metrics/autocomplete/tagValue?metricName=signoz_calls_total&tagKey=${props}`,+ `/metrics/autocomplete/tagValue?metricName=${props.metricName}&tagKey=${props.tagKey}`,);return {diff --git a/frontend/src/components/Editor/index.tsx b/frontend/src/components/Editor/index.tsxindex 0ed486e248..92033b0830 100644--- a/frontend/src/components/Editor/index.tsx+++ b/frontend/src/components/Editor/index.tsx@@ -1,38 +1,46 @@-import MEditor from '@monaco-editor/react';+import MEditor, { EditorProps } from '@monaco-editor/react';import React from 'react';+import { useSelector } from 'react-redux';+import { AppState } from 'store/reducers';+import AppReducer from 'types/reducer/app';function Editor({value,- language = 'yaml',+ language,onChange,- readOnly = false,-}: EditorProps): JSX.Element {+ readOnly,+ height,+ options,+}: MEditorProps): JSX.Element {+ const { isDarkMode } = useSelector<AppState, AppReducer>((state) => state.app);return (<MEditor- theme="vs-dark"+ theme={isDarkMode ? 'vs-dark' : 'vs-light'}language={language}value={value}- options={{ fontSize: 16, automaticLayout: true, readOnly }}- height="40vh"+ options={{ fontSize: 16, automaticLayout: true, readOnly, ...options }}+ height={height}onChange={(newValue): void => {- if (newValue) {- onChange(newValue);- }+ if (typeof newValue === 'string') onChange(newValue);}}/>);}-interface EditorProps {+interface MEditorProps {value: string;language?: string;onChange: (value: string) => void;readOnly?: boolean;+ height?: string;+ options?: EditorProps['options'];}Editor.defaultProps = {- language: undefined,+ language: 'yaml',readOnly: false,+ height: '40vh',+ options: {},};export default Editor;diff --git a/frontend/src/components/Graph/Plugin/Legend.ts b/frontend/src/components/Graph/Plugin/Legend.tsindex b8ec2facf9..51ec58df2e 100644--- a/frontend/src/components/Graph/Plugin/Legend.ts+++ b/frontend/src/components/Graph/Plugin/Legend.ts@@ -22,7 +22,6 @@ const getOrCreateLegendList = (listContainer.style.height = '100%';listContainer.style.flexWrap = 'wrap';listContainer.style.justifyContent = 'center';-legendContainer?.appendChild(listContainer);}diff --git a/frontend/src/components/Graph/index.tsx b/frontend/src/components/Graph/index.tsxindex 2194387dd4..4bb76276c0 100644--- a/frontend/src/components/Graph/index.tsx+++ b/frontend/src/components/Graph/index.tsx@@ -182,11 +182,10 @@ function Graph({};const chartHasData = hasData(data);const chartPlugins = [];- if (chartHasData) {- chartPlugins.push(legend(name, data.datasets.length > 3));- } else {- chartPlugins.push(emptyGraph);- }++ if (!chartHasData) chartPlugins.push(emptyGraph);+ chartPlugins.push(legend(name, data.datasets.length > 3));+lineChartRef.current = new Chart(chartRef.current, {type,data,diff --git a/frontend/src/components/Graph/xAxisConfig.ts b/frontend/src/components/Graph/xAxisConfig.tsindex 565b60f7e0..d14d9bba09 100644--- a/frontend/src/components/Graph/xAxisConfig.ts+++ b/frontend/src/components/Graph/xAxisConfig.ts@@ -109,14 +109,14 @@ export const useXAxisTimeUnit = (data: Chart['data']): IAxisTimeConfig => {let minTime = Number.POSITIVE_INFINITY;let maxTime = Number.NEGATIVE_INFINITY;data?.labels?.forEach((timeStamp: unknown): void => {- const getTimeStamp = (time: string | number): Date | number | string => {- if (typeof timeStamp === 'string') {- return Date.parse(timeStamp);+ const getTimeStamp = (time: Date | number): Date | number | string => {+ if (time instanceof Date) {+ return Date.parse(time.toString());}return time;};- const time = getTimeStamp(timeStamp as string | number);+ const time = getTimeStamp(timeStamp as Date | number);minTime = Math.min(parseInt(time.toString(), 10), minTime);maxTime = Math.max(parseInt(time.toString(), 10), maxTime);diff --git a/frontend/src/components/Graph/yAxisConfig.ts b/frontend/src/components/Graph/yAxisConfig.tsindex 5d1eeb5da7..44377b6fc5 100644--- a/frontend/src/components/Graph/yAxisConfig.ts+++ b/frontend/src/components/Graph/yAxisConfig.ts@@ -7,13 +7,17 @@ export const getYAxisFormattedValue = (let decimalPrecision: number | undefined;const parsedValue = getValueFormat(format)(parseFloat(value),- undefined,- undefined,+ 12,+ 12,undefined,);+try {const decimalSplitted = parsedValue.text.split('.');- if (decimalSplitted.length === 1) {+ if (+ decimalSplitted.length === 1 ||+ parseFloat(parsedValue.text) === parseInt(parsedValue.text, 10)+ ) {decimalPrecision = 0;} else {const decimalDigits = decimalSplitted[1].split('');diff --git a/frontend/src/components/TextToolTip/index.tsx b/frontend/src/components/TextToolTip/index.tsxindex 051d48c30d..06802b475f 100644--- a/frontend/src/components/TextToolTip/index.tsx+++ b/frontend/src/components/TextToolTip/index.tsx@@ -10,9 +10,11 @@ function TextToolTip({ text, url }: TextToolTipProps): JSX.Element {return (<div>{`${text} `}- <a href={url} rel="noopener noreferrer" target="_blank">- here- </a>+ {url && (+ <a href={url} rel="noopener noreferrer" target="_blank">+ here+ </a>+ )}</div>);}}diff --git a/frontend/src/constants/dashboard.ts b/frontend/src/constants/dashboard.tsnew file mode 100644index 0000000000..3aa495d6b8--- /dev/null+++ b/frontend/src/constants/dashboard.ts@@ -0,0 +1,33 @@+import { EAggregateOperator, EReduceOperator } from 'types/common/dashboard';++export const PromQLQueryTemplate = {+ query: '',+ legend: '',+ disabled: false,+};++export const ClickHouseQueryTemplate = {+ rawQuery: '',+ legend: '',+ disabled: false,+};++export const QueryBuilderQueryTemplate = {+ metricName: null,+ aggregateOperator: EAggregateOperator.NOOP,+ tagFilters: {+ op: 'AND',+ items: [],+ },+ legend: '',+ disabled: false,+ // Specific to TIME_SERIES type graph+ groupBy: [],+ // Specific to VALUE type graph+ reduceTo: EReduceOperator['Latest of values in timeframe'],+};++export const QueryBuilderFormulaTemplate = {+ expression: '',+ disabled: false,+};diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/index.metricsBuilder.tsx b/frontend/src/container/GridGraphLayout/Graph/FullView/index.metricsBuilder.tsxnew file mode 100644index 0000000000..8fe3b259c1--- /dev/null+++ b/frontend/src/container/GridGraphLayout/Graph/FullView/index.metricsBuilder.tsx@@ -0,0 +1,132 @@+import { Button, Typography } from 'antd';+import { GraphOnClickHandler } from 'components/Graph';+import Spinner from 'components/Spinner';+import TimePreference from 'components/TimePreferenceDropDown';+import GridGraphComponent from 'container/GridGraphComponent';+import {+ timeItems,+ timePreferance,+} from 'container/NewWidget/RightContainer/timeItems';+import getChartData from 'lib/getChartData';+import React, { useCallback, useState } from 'react';+import { useQuery } from 'react-query';+import { useSelector } from 'react-redux';+import { GetMetricQueryRange } from 'store/actions/dashboard/getQueryResults';+import { AppState } from 'store/reducers';+import { ErrorResponse, SuccessResponse } from 'types/api';+import { Widgets } from 'types/api/dashboard/getAll';+import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';+import { GlobalReducer } from 'types/reducer/globalTime';++import { NotFoundContainer, TimeContainer } from './styles';++function FullView({+ widget,+ fullViewOptions = true,+ onClickHandler,+ name,+ yAxisUnit,+}: FullViewProps): JSX.Element {+ const { selectedTime: globalSelectedTime } = useSelector<+ AppState,+ GlobalReducer+ >((state) => state.globalTime);++ const getSelectedTime = useCallback(+ () =>+ timeItems.find((e) => e.enum === (widget?.timePreferance || 'GLOBAL_TIME')),+ [widget],+ );++ const [selectedTime, setSelectedTime] = useState<timePreferance>({+ name: getSelectedTime()?.name || '',+ enum: widget?.timePreferance || 'GLOBAL_TIME',+ });+ const response = useQuery<+ SuccessResponse<MetricRangePayloadProps> | ErrorResponse+ >(+ `FullViewGetMetricsQueryRange-${selectedTime.enum}-${globalSelectedTime}`,+ () =>+ GetMetricQueryRange({+ selectedTime: selectedTime.enum,+ graphType: widget.panelTypes,+ query: widget.query,+ globalSelectedInterval: globalSelectedTime,+ }),+ );++ const isError = response?.error;+ const isLoading = response.isLoading === true;+ const errorMessage = isError instanceof Error ? isError?.message : '';++ if (isLoading) {+ return <Spinner height="100%" size="large" tip="Loading..." />;+ }+ if (isError || !response?.data?.payload?.data?.result) {+ return (+ <NotFoundContainer>+ <Typography>{errorMessage}</Typography>+ </NotFoundContainer>+ );+ }++ return (+ <>+ {fullViewOptions && (+ <TimeContainer>+ <TimePreference+ {...{+ selectedTime,+ setSelectedTime,+ }}+ />+ <Button+ onClick={(): void => {+ response.refetch();+ }}+ type="primary"+ >+ Refresh+ </Button>+ </TimeContainer>+ )}++ <GridGraphComponent+ {...{+ GRAPH_TYPES: widget.panelTypes,+ data: getChartData({+ queryData: [+ {+ queryData: response.data?.payload?.data?.result+ ? response.data?.payload?.data?.result+ : [],+ },+ ],+ }),+ isStacked: widget.isStacked,+ opacity: widget.opacity,+ title: widget.title,+ onClickHandler,+ name,+ yAxisUnit,+ }}+ />+ </>+ );+}++interface FullViewProps {+ widget: Widgets;+ fullViewOptions?: boolean;+ onClickHandler?: GraphOnClickHandler;+ name: string;+ yAxisUnit?: string;+}++FullView.defaultProps = {+ fullViewOptions: undefined,+ onClickHandler: undefined,+ yAxisUnit: undefined,+};++export default FullView;diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsx b/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsxindex 3111e33e87..ad228f642e 100644--- a/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsx+++ b/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsx@@ -19,7 +19,7 @@ import React, { useCallback, useState } from 'react';import { useQueries } from 'react-query';import { useSelector } from 'react-redux';import { AppState } from 'store/reducers';-import { Widgets } from 'types/api/dashboard/getAll';+import { PromQLWidgets } from 'types/api/dashboard/getAll';import { GlobalReducer } from 'types/reducer/globalTime';import { NotFoundContainer, TimeContainer } from './styles';@@ -173,7 +173,7 @@ function FullView({}interface FullViewProps {- widget: Widgets;+ widget: PromQLWidgets;fullViewOptions?: boolean;onClickHandler?: GraphOnClickHandler;name: string;diff --git a/frontend/src/container/GridGraphLayout/Graph/index.tsx b/frontend/src/container/GridGraphLayout/Graph/index.tsxindex a57a396fd0..f39d64cb76 100644--- a/frontend/src/container/GridGraphLayout/Graph/index.tsx+++ b/frontend/src/container/GridGraphLayout/Graph/index.tsx@@ -1,14 +1,12 @@import { Typography } from 'antd';-import getQueryResult from 'api/widgets/getQuery';+import { AxiosError } from 'axios';+import { ChartData } from 'chart.js';import Spinner from 'components/Spinner';import GridGraphComponent from 'container/GridGraphComponent';import getChartData from 'lib/getChartData';-import GetMaxMinTime from 'lib/getMaxMinTime';-import GetStartAndEndTime from 'lib/getStartAndEndTime';import isEmpty from 'lodash-es/isEmpty';-import React, { memo, useCallback, useState } from 'react';+import React, { memo, useCallback, useEffect, useState } from 'react';import { Layout } from 'react-grid-layout';-import { useQueries } from 'react-query';import { connect, useSelector } from 'react-redux';import { bindActionCreators, Dispatch } from 'redux';import { ThunkDispatch } from 'redux-thunk';@@ -16,15 +14,17 @@ import {DeleteWidget,DeleteWidgetProps,} from 'store/actions/dashboard/deleteWidget';+import { GetMetricQueryRange } from 'store/actions/dashboard/getQueryResults';import { AppState } from 'store/reducers';import AppActions from 'types/actions';import { GlobalTime } from 'types/actions/globalTime';import { Widgets } from 'types/api/dashboard/getAll';+import { GlobalReducer } from 'types/reducer/globalTime';import { LayoutProps } from '..';import EmptyWidget from '../EmptyWidget';import WidgetHeader from '../WidgetHeader';-import FullView from './FullView';+import FullView from './FullView/index.metricsBuilder';import { ErrorContainer, FullViewContainer, Modal } from './styles';function GridCardGraph({@@ -35,60 +35,118 @@ function GridCardGraph({layout = [],setLayout,}: GridCardGraphProps): JSX.Element {+ const [state, setState] = useState<GridCardGraphState>({+ loading: true,+ errorMessage: '',+ error: false,+ payload: undefined,+ });const [hovered, setHovered] = useState(false);const [modal, setModal] = useState(false);+ const [deleteModal, setDeleteModal] = useState(false);+const { minTime, maxTime } = useSelector<AppState, GlobalTime>((state) => state.globalTime,);- const [deleteModal, setDeleteModal] = useState(false);+ const { selectedTime: globalSelectedInterval } = useSelector<+ AppState,+ GlobalReducer+ >((state) => state.globalTime);- const getMaxMinTime = GetMaxMinTime({- graphType: widget?.panelTypes,- maxTime,- minTime,- });+ // const getMaxMinTime = GetMaxMinTime({+ // graphType: widget?.panelTypes,+ // maxTime,+ // minTime,+ // });- const { start, end } = GetStartAndEndTime({- type: widget?.timePreferance,- maxTime: getMaxMinTime.maxTime,- minTime: getMaxMinTime.minTime,- });+ // const { start, end } = GetStartAndEndTime({+ // type: widget?.timePreferance,+ // maxTime: getMaxMinTime.maxTime,+ // minTime: getMaxMinTime.minTime,+ // });- const queryLength = widget?.query?.filter((e) => e.query.length !== 0) || [];-- const response = useQueries(- queryLength?.map((query) => {- return {- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type- queryFn: () => {- return getQueryResult({- end,- query: query?.query,- start,- step: '60',- });- },- queryHash: `${query?.query}-${query?.legend}-${start}-${end}`,- retryOnMount: false,- };- }),- );+ // const queryLength = widget?.query?.filter((e) => e.query.length !== 0) || [];- const isError =- response.find((e) => e?.data?.statusCode !== 200) !== undefined ||- response.some((e) => e.isError === true);+ // const response = useQueries(+ // queryLength?.map((query) => {+ // return {+ // // eslint-disable-next-line @typescript-eslint/explicit-function-return-type+ // queryFn: () => {+ // return getQueryResult({+ // end,+ // query: query?.query,+ // start,+ // step: '60',+ // });+ // },+ // queryHash: `${query?.query}-${query?.legend}-${start}-${end}`,+ // retryOnMount: false,+ // };+ // }),+ // );- const isLoading = response.some((e) => e.isLoading === true);+ // const isError =+ // response.find((e) => e?.data?.statusCode !== 200) !== undefined ||+ // response.some((e) => e.isError === true);- const errorMessage = response.find((e) => e.data?.error !== null)?.data?.error;+ // const isLoading = response.some((e) => e.isLoading === true);- const data = response.map((responseOfQuery) =>- responseOfQuery?.data?.payload?.result.map((e, index) => ({- query: queryLength[index]?.query,- queryData: e,- legend: queryLength[index]?.legend,- })),- );+ // const errorMessage = response.find((e) => e.data?.error !== null)?.data?.error;++ // const data = response.map((responseOfQuery) =>+ // responseOfQuery?.data?.payload?.result.map((e, index) => ({+ // query: queryLength[index]?.query,+ // queryData: e,+ // legend: queryLength[index]?.legend,+ // })),+ // );++ useEffect(() => {+ (async (): Promise<void> => {+ try {+ const response = await GetMetricQueryRange({+ selectedTime: widget.timePreferance,+ graphType: widget.panelTypes,+ query: widget.query,+ globalSelectedInterval,+ });++ const isError = response.error;++ if (isError != null) {+ setState((state) => ({+ ...state,+ error: true,+ errorMessage: isError || 'Something went wrong',+ loading: false,+ }));+ } else {+ const chartDataSet = getChartData({+ queryData: [+ {+ queryData: response.payload?.data?.result+ ? response.payload?.data?.result+ : [],+ },+ ],+ });++ setState((state) => ({+ ...state,+ loading: false,+ payload: chartDataSet,+ }));+ }+ } catch (error) {+ setState((state) => ({+ ...state,+ error: true,+ errorMessage: (error as AxiosError).toString(),+ loading: false,+ }));+ }+ })();+ }, [widget, maxTime, minTime, globalSelectedInterval]);const onToggleModal = useCallback((func: React.Dispatch<React.SetStateAction<boolean>>) => {@@ -144,14 +202,7 @@ function GridCardGraph({const isEmptyLayout = widget?.id === 'empty' || isEmpty(widget);- if (isLoading) {- return <Spinner height="20vh" tip="Loading..." />;- }-- if (- (isError || data === undefined || data[0] === undefined) &&- !isEmptyLayout- ) {+ if (state.error && !isEmptyLayout) {return (<>{getModals()}@@ -163,18 +214,17 @@ function GridCardGraph({onDelete={(): void => onToggleModal(setDeleteModal)}/>- <ErrorContainer>{errorMessage}</ErrorContainer>+ <ErrorContainer>{state.errorMessage}</ErrorContainer></>);}- const chartData = getChartData({- queryData: data.map((e) => ({- query: e?.map((e) => e.query).join(' ') || '',- queryData: e?.map((e) => e.queryData) || [],- legend: e?.map((e) => e.legend).join('') || '',- })),- });+ if (+ (state.loading === true || state.payload === undefined) &&+ !isEmptyLayout+ ) {+ return <Spinner height="20vh" tip="Loading..." />;+ }return (<span@@ -203,11 +253,11 @@ function GridCardGraph({{!isEmptyLayout && getModals()}- {!isEmpty(widget) && (+ {!isEmpty(widget) && !!state.payload && (<GridGraphComponent{...{GRAPH_TYPES: widget.panelTypes,- data: chartData,+ data: state.payload,isStacked: widget.isStacked,opacity: widget.opacity,title: ' ', // empty title to accommodate absolutely positioned widget header@@ -222,6 +272,13 @@ function GridCardGraph({);}+interface GridCardGraphState {+ loading: boolean;+ error: boolean;+ errorMessage: string;+ payload: ChartData | undefined;+}+interface DispatchProps {deleteWidget: ({widgetId,diff --git a/frontend/src/container/GridGraphLayout/utils.ts b/frontend/src/container/GridGraphLayout/utils.tsindex 67b854368c..c2c762e1f7 100644--- a/frontend/src/container/GridGraphLayout/utils.ts+++ b/frontend/src/container/GridGraphLayout/utils.ts@@ -1,9 +1,16 @@import { notification } from 'antd';import updateDashboardApi from 'api/dashboard/update';+import {+ ClickHouseQueryTemplate,+ PromQLQueryTemplate,+ QueryBuilderQueryTemplate,+} from 'constants/dashboard';import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';+import GetQueryName from 'lib/query/GetQueryName';import { Layout } from 'react-grid-layout';import store from 'store';import { Dashboard } from 'types/api/dashboard/getAll';+import { EQueryType } from 'types/common/dashboard';export const UpdateDashboard = async ({data,@@ -29,12 +36,31 @@ export const UpdateDashboard = async ({nullZeroValues: '',opacity: '',panelTypes: graphType,- query: [- {- query: '',- legend: '',+ queryType: 0,+ query: {+ queryType: EQueryType.QUERY_BUILDER,+ promQL: [+ {+ name: GetQueryName([]),+ ...PromQLQueryTemplate,+ },+ ],+ clickHouse: [+ {+ name: GetQueryName([]),+ ...ClickHouseQueryTemplate,+ },+ ],+ metricsBuilder: {+ formulas: [],+ queryBuilder: [+ {+ name: GetQueryName([]),+ ...QueryBuilderQueryTemplate,+ },+ ],},- ],+ },queryData: {data: [],error: false,diff --git a/frontend/src/container/MetricsApplication/ResourceAttributesFilter/utils.ts b/frontend/src/container/MetricsApplication/ResourceAttributesFilter/utils.tsindex e8dd7bb503..aa16f160ac 100644--- a/frontend/src/container/MetricsApplication/ResourceAttributesFilter/utils.ts+++ b/frontend/src/container/MetricsApplication/ResourceAttributesFilter/utils.ts@@ -21,7 +21,10 @@ export const GetTagKeys = async (): Promise<IOption[]> => {// resolve(TagKeysCache);// });// }- const { payload } = await getResourceAttributesTagKeys();+ const { payload } = await getResourceAttributesTagKeys({+ metricName: 'signoz_calls_total',+ match: 'resource_',+ });if (!payload || !payload?.data) {return [];}@@ -32,12 +35,15 @@ export const GetTagKeys = async (): Promise<IOption[]> => {};export const GetTagValues = async (tagKey: string): Promise<IOption[]> => {- const { payload } = await getResourceAttributesTagValues(tagKey);+ const { payload } = await getResourceAttributesTagValues({+ tagKey,+ metricName: 'signoz_calls_total',+ });if (!payload || !payload?.data) {return [];}- return payload.data.filter(Boolean).map((tagValue: string) => ({+ return payload.data.map((tagValue: string) => ({label: tagValue,value: tagValue,}));diff --git a/frontend/src/container/MetricsApplication/Tabs/DBCall.tsx b/frontend/src/container/MetricsApplication/Tabs/DBCall.tsxindex ba0af031cd..b5466f2b02 100644--- a/frontend/src/container/MetricsApplication/Tabs/DBCall.tsx+++ b/frontend/src/container/MetricsApplication/Tabs/DBCall.tsx@@ -4,7 +4,7 @@ import React from 'react';import { useSelector } from 'react-redux';import { useParams } from 'react-router-dom';import { AppState } from 'store/reducers';-import { Widgets } from 'types/api/dashboard/getAll';+import { PromQLWidgets, Widgets } from 'types/api/dashboard/getAll';import MetricReducer from 'types/reducer/metrics';import { Card, GraphContainer, GraphTitle, Row } from '../styles';@@ -58,7 +58,7 @@ function DBCall({ getWidget }: DBCallProps): JSX.Element {}interface DBCallProps {- getWidget: (query: Widgets['query']) => Widgets;+ getWidget: (query: PromQLWidgets['query']) => PromQLWidgets;}export default DBCall;diff --git a/frontend/src/container/MetricsApplication/Tabs/External.tsx b/frontend/src/container/MetricsApplication/Tabs/External.tsxindex 73eca09600..2974ba3f38 100644--- a/frontend/src/container/MetricsApplication/Tabs/External.tsx+++ b/frontend/src/container/MetricsApplication/Tabs/External.tsx@@ -4,7 +4,7 @@ import React from 'react';import { useSelector } from 'react-redux';import { useParams } from 'react-router-dom';import { AppState } from 'store/reducers';-import { Widgets } from 'types/api/dashboard/getAll';+import { PromQLWidgets } from 'types/api/dashboard/getAll';import MetricReducer from 'types/reducer/metrics';import { Card, GraphContainer, GraphTitle, Row } from '../styles';@@ -102,7 +102,7 @@ function External({ getWidget }: ExternalProps): JSX.Element {}interface ExternalProps {- getWidget: (query: Widgets['query']) => Widgets;+ getWidget: (query: PromQLWidgets['query']) => PromQLWidgets;}export default External;diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview.tsxindex fbc1a855ac..a24e67aeb7 100644--- a/frontend/src/container/MetricsApplication/Tabs/Overview.tsx+++ b/frontend/src/container/MetricsApplication/Tabs/Overview.tsx@@ -11,7 +11,7 @@ import React, { useRef } from 'react';import { useSelector } from 'react-redux';import { useParams } from 'react-router-dom';import { AppState } from 'store/reducers';-import { Widgets } from 'types/api/dashboard/getAll';+import { PromQLWidgets } from 'types/api/dashboard/getAll';import MetricReducer from 'types/reducer/metrics';import { Card, Col, GraphContainer, GraphTitle, Row } from '../styles';@@ -42,8 +42,7 @@ function Application({ getWidget }: DashboardProps): JSX.Element {urlParams.set(METRICS_PAGE_QUERY_PARAM.endTime, tPlusOne.toString());history.replace(- `${- ROUTES.TRACE+ `${ROUTES.TRACE}?${urlParams.toString()}&selected={"serviceName":["${servicename}"]}&filterToFetchData=["duration","status","serviceName"]&spanAggregateCurrentPage=1&selectedTags=${selectedTraceTags}&&isFilterExclude={"serviceName":false}&userSelectedFilter={"status":["error","ok"],"serviceName":["${servicename}"]}&spanAggregateCurrentPage=1&spanAggregateOrder=ascend`,);};@@ -94,8 +93,7 @@ function Application({ getWidget }: DashboardProps): JSX.Element {urlParams.set(METRICS_PAGE_QUERY_PARAM.endTime, tPlusOne.toString());history.replace(- `${- ROUTES.TRACE+ `${ROUTES.TRACE}?${urlParams.toString()}?selected={"serviceName":["${servicename}"],"status":["error"]}&filterToFetchData=["duration","status","serviceName"]&spanAggregateCurrentPage=1&selectedTags=${selectedTraceTags}&isFilterExclude={"serviceName":false,"status":false}&userSelectedFilter={"serviceName":["${servicename}"],"status":["error"]}&spanAggregateCurrentPage=1&spanAggregateOrder=ascend`,);};@@ -248,7 +246,7 @@ function Application({ getWidget }: DashboardProps): JSX.Element {}interface DashboardProps {- getWidget: (query: Widgets['query']) => Widgets;+ getWidget: (query: PromQLWidgets['query']) => PromQLWidgets;}export default Application;diff --git a/frontend/src/container/MetricsApplication/index.tsx b/frontend/src/container/MetricsApplication/index.tsxindex 9922fbb8c2..aeaf4a5664 100644--- a/frontend/src/container/MetricsApplication/index.tsx+++ b/frontend/src/container/MetricsApplication/index.tsx@@ -3,14 +3,14 @@ import ROUTES from 'constants/routes';import React from 'react';import { generatePath, useParams } from 'react-router-dom';import { useLocation } from 'react-use';-import { Widgets } from 'types/api/dashboard/getAll';+import { PromQLWidgets } from 'types/api/dashboard/getAll';import ResourceAttributesFilter from './ResourceAttributesFilter';import DBCall from './Tabs/DBCall';import External from './Tabs/External';import Overview from './Tabs/Overview';-const getWidget = (query: Widgets['query']): Widgets => {+const getWidget = (query: PromQLWidgets['query']): PromQLWidgets => {return {description: '',id: '',diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/Query.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/Query.tsxdeleted file mode 100644index 916771eece..0000000000--- a/frontend/src/container/NewWidget/LeftContainer/QuerySection/Query.tsx+++ /dev/null@@ -1,151 +0,0 @@-import { Button, Divider } from 'antd';-import Input from 'components/Input';-import TextToolTip from 'components/TextToolTip';-import { timePreferance } from 'container/NewWidget/RightContainer/timeItems';-import React, { useCallback, useMemo, useState } from 'react';-import { connect, useSelector } from 'react-redux';-import { useLocation } from 'react-router-dom';-import { bindActionCreators, Dispatch } from 'redux';-import { ThunkDispatch } from 'redux-thunk';-import { DeleteQuery } from 'store/actions';-import {- UpdateQuery,- UpdateQueryProps,-} from 'store/actions/dashboard/updateQuery';-import { AppState } from 'store/reducers';-import AppActions from 'types/actions';-import { DeleteQueryProps } from 'types/actions/dashboard';-import { Widgets } from 'types/api/dashboard/getAll';-import DashboardReducer from 'types/reducer/dashboards';--import {- ButtonContainer,- Container,- InputContainer,- QueryWrapper,-} from './styles';--function Query({- currentIndex,- preLegend,- preQuery,- updateQuery,- deleteQuery,-}: QueryProps): JSX.Element {- const [promqlQuery, setPromqlQuery] = useState(preQuery);- const [legendFormat, setLegendFormat] = useState(preLegend);- const { search } = useLocation();- const { dashboards } = useSelector<AppState, DashboardReducer>(- (state) => state.dashboards,- );-- const [selectedDashboards] = dashboards;- const { widgets } = selectedDashboards.data;-- const query = new URLSearchParams(search);- const widgetId = query.get('widgetId') || '';-- const urlQuery = useMemo(() => {- return new URLSearchParams(search);- }, [search]);-- const getWidget = useCallback(() => {- const widgetId = urlQuery.get('widgetId');- return widgets?.find((e) => e.id === widgetId);- }, [widgets, urlQuery]);-- const selectedWidget = getWidget() as Widgets;-- const onChangeHandler = useCallback(- (setFunc: React.Dispatch<React.SetStateAction<string>>, value: string) => {- setFunc(value);- },- [],- );-- const onBlurHandler = (): void => {- updateQuery({- currentIndex,- legend: legendFormat,- query: promqlQuery,- widgetId,- yAxisUnit: selectedWidget.yAxisUnit,- });- };-- const onDeleteQueryHandler = (): void => {- deleteQuery({- widgetId,- currentIndex,- });- };-- return (- <>- <Container>- <QueryWrapper>- <InputContainer>- <Input- onChangeHandler={(event): void =>- onChangeHandler(setPromqlQuery, event.target.value)- }- size="middle"- value={promqlQuery}- addonBefore="PromQL Query"- onBlur={(): void => onBlurHandler()}- />- </InputContainer>-- <InputContainer>- <Input- onChangeHandler={(event): void =>- onChangeHandler(setLegendFormat, event.target.value)- }- size="middle"- value={legendFormat}- addonBefore="Legend Format"- onBlur={(): void => onBlurHandler()}- />- </InputContainer>- </QueryWrapper>-- <ButtonContainer>- <Button onClick={onDeleteQueryHandler}>Delete</Button>- <TextToolTip- {...{- text: `More details on how to plot metrics graphs`,- url: 'https://signoz.io/docs/userguide/send-metrics/#related-videos',- }}- />- </ButtonContainer>- </Container>-- <Divider />- </>- );-}--interface DispatchProps {- updateQuery: (- props: UpdateQueryProps,- ) => (dispatch: Dispatch<AppActions>) => void;- deleteQuery: (- props: DeleteQueryProps,- ) => (dispatch: Dispatch<AppActions>) => void;-}--const mapDispatchToProps = (- dispatch: ThunkDispatch<unknown, unknown, AppActions>,-): DispatchProps => ({- updateQuery: bindActionCreators(UpdateQuery, dispatch),- deleteQuery: bindActionCreators(DeleteQuery, dispatch),-});--interface QueryProps extends DispatchProps {- selectedTime: timePreferance;- currentIndex: number;- preQuery: string;- preLegend: string;-}--export default connect(null, mapDispatchToProps)(Query);diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/Options.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/Options.tsnew file mode 100644index 0000000000..80a14f173b--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/Options.ts@@ -0,0 +1,20 @@+import { EAggregateOperator } from 'types/common/dashboard';++export const AggregateFunctions = Object.keys(EAggregateOperator)+ .filter((key) => Number.isNaN(parseInt(key, 10)))+ .map((key) => {+ return {+ label: key,+ value: EAggregateOperator[key],+ };+ });++export const TagKeyOperator = [+ { label: 'In', value: 'IN' },+ { label: 'Not In', value: 'NIN' },+ { label: 'Like', value: 'LIKE' },+ { label: 'Not Like', value: 'NLIKE' },+ // { label: 'Equal', value: 'EQ' },+ // { label: 'Not Equal', value: 'NEQ' },+ // { label: 'REGEX', value: 'REGEX' },+];diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/QueryHeader.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/QueryHeader.tsxnew file mode 100644index 0000000000..9164c532af--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/QueryHeader.tsx@@ -0,0 +1,46 @@+import {+ DeleteOutlined,+ DownOutlined,+ EyeFilled,+ EyeInvisibleFilled,+ RightOutlined,+} from '@ant-design/icons';+import { Button, Row } from 'antd';+import React, { useState } from 'react';++import { QueryWrapper } from '../styles';++function QueryHeader({+ disabled,+ onDisable,+ name,+ onDelete,+ children,+}): JSX.Element {+ const [collapse, setCollapse] = useState(false);+ return (+ <QueryWrapper>+ <Row style={{ justifyContent: 'space-between' }}>+ <Row>+ <Button+ type="ghost"+ icon={disabled ? <EyeInvisibleFilled /> : <EyeFilled />}+ onClick={onDisable}+ >+ {name}+ </Button>+ <Button+ type="ghost"+ icon={collapse ? <RightOutlined /> : <DownOutlined />}+ onClick={(): void => setCollapse(!collapse)}+ />+ </Row>++ <Button type="ghost" danger icon={<DeleteOutlined />} onClick={onDelete} />+ </Row>+ {!collapse && children}+ </QueryWrapper>+ );+}++export default QueryHeader;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/clickHouse/index.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/clickHouse/index.tsxnew file mode 100644index 0000000000..cabd7470b8--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/clickHouse/index.tsx@@ -0,0 +1,69 @@+import { PlusOutlined } from '@ant-design/icons';+import { ClickHouseQueryTemplate } from 'constants/dashboard';+import GetQueryName from 'lib/query/GetQueryName';+import React from 'react';++import { WIDGET_CLICKHOUSE_QUERY_KEY_NAME } from '../../constants';+import { QueryButton } from '../../styles';+import ClickHouseQueryBuilder from './query';++function ClickHouseQueryContainer({+ queryData,+ updateQueryData,+ clickHouseQueries,+}): JSX.Element | null {+ const handleClickHouseQueryChange = ({+ queryIndex,+ rawQuery,+ legend,+ toggleDisable,+ toggleDelete,+ }): void => {+ const allQueries = queryData[WIDGET_CLICKHOUSE_QUERY_KEY_NAME];+ const currentIndexQuery = allQueries[queryIndex];++ if (rawQuery !== undefined) {+ currentIndexQuery.rawQuery = rawQuery;+ }++ if (legend !== undefined) {+ currentIndexQuery.legend = legend;+ }++ if (toggleDisable) {+ currentIndexQuery.disabled = !currentIndexQuery.disabled;+ }+ if (toggleDelete) {+ allQueries.splice(queryIndex, 1);+ }+ updateQueryData({ updatedQuery: { ...queryData } });+ };+ const addQueryHandler = (): void => {+ queryData[WIDGET_CLICKHOUSE_QUERY_KEY_NAME].push({+ name: GetQueryName(queryData[WIDGET_CLICKHOUSE_QUERY_KEY_NAME]),+ ...ClickHouseQueryTemplate,+ });+ updateQueryData({ updatedQuery: { ...queryData } });+ };++ if (!clickHouseQueries) {+ return null;+ }+ return (+ <>+ {clickHouseQueries.map((q, idx) => (+ <ClickHouseQueryBuilder+ key={q.name}+ queryIndex={idx}+ queryData={q}+ handleQueryChange={handleClickHouseQueryChange}+ />+ ))}+ <QueryButton onClick={addQueryHandler} icon={<PlusOutlined />}>+ Query+ </QueryButton>+ </>+ );+}++export default ClickHouseQueryContainer;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/clickHouse/query.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/clickHouse/query.tsxnew file mode 100644index 0000000000..f51ffbf08b--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/clickHouse/query.tsx@@ -0,0 +1,53 @@+import { Input } from 'antd';+import MonacoEditor from 'components/Editor';+import React from 'react';++import QueryHeader from '../QueryHeader';++function ClickHouseQueryBuilder({+ queryData,+ queryIndex,+ handleQueryChange,+}): JSX.Element | null {+ if (queryData === undefined) {+ return null;+ }++ return (+ <QueryHeader+ name={queryData.name}+ disabled={queryData.disabled}+ onDisable={(): void =>+ handleQueryChange({ queryIndex, toggleDisable: true })+ }+ onDelete={(): void => {+ handleQueryChange({ queryIndex, toggleDelete: true });+ }}+ >+ <MonacoEditor+ language="sql"+ theme="vs-dark"+ height="200px"+ onChange={(value): void =>+ handleQueryChange({ queryIndex, rawQuery: value })+ }+ value={queryData.rawQuery}+ options={{+ scrollbar: {+ alwaysConsumeMouseWheel: false,+ },+ }}+ />+ <Input+ onChange={(event): void =>+ handleQueryChange({ queryIndex, legend: event.target.value })+ }+ size="middle"+ defaultValue={queryData.legend}+ addonBefore="Legend Format"+ />+ </QueryHeader>+ );+}++export default ClickHouseQueryBuilder;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/index.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/index.tsxnew file mode 100644index 0000000000..ba01fb0389--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/index.tsx@@ -0,0 +1,95 @@+import {+ DeleteOutlined,+ DownOutlined,+ EyeFilled,+ RightOutlined,+} from '@ant-design/icons';+import { Button, Row } from 'antd';+import MonacoEditor from 'components/Editor';+import React, { useState } from 'react';+import { useSelector } from 'react-redux';+import { AppState } from 'store/reducers';+import AppReducer from 'types/reducer/app';++import { QueryBuilderWrapper, QueryWrapper } from '../styles';+import { TQueryCategories } from '../types';+import PromQLQueryBuilder from './promQL/promQL';+import MetricsBuilder from './queryBuilder/query';++function QueryBuilder({+ name,+ onDelete,+ queryCategory,+ queryData,+ updateQueryData,+}: QueryBuilderProps): JSX.Element {+ const { isDarkMode } = useSelector<AppState, AppReducer>((state) => state.app);+ const [hideFromUI, setHideFromUI] = useState<boolean>(false);+ const handleHideFromUI = (): void => {+ setHideFromUI(!hideFromUI);+ };+ const handleClickhouseQueryChange = (clickHouseQuery): void => {+ if (clickHouseQuery !== null) {+ queryData.clickHouseQuery = clickHouseQuery;+ }+ updateQueryData(queryData);+ };+ const handlePromQLQueryChange = ({ query, legend }): void => {+ if (query) queryData.promQL.query = query;+ if (legend) queryData.promQL.legend = legend;++ updateQueryData(queryData);+ };++ return (+ <QueryWrapper>+ <Row style={{ justifyContent: 'space-between' }}>+ <Row>+ <Button type="ghost" icon={<EyeFilled />}>+ {name}+ </Button>+ <Button+ type="ghost"+ icon={hideFromUI ? <RightOutlined /> : <DownOutlined />}+ onClick={handleHideFromUI}+ />+ </Row>++ <Button type="ghost" danger icon={<DeleteOutlined />} onClick={onDelete} />+ </Row>+ {!hideFromUI && (+ <QueryBuilderWrapper isDarkMode={isDarkMode}>+ {queryCategory === 0 ? (+ <MetricsBuilder+ queryData={queryData}+ updateQueryData={updateQueryData}+ metricName={queryData.queryBuilder.metricName}+ />+ ) : queryCategory === 1 ? (+ <MonacoEditor+ language="sql"+ theme="vs-dark"+ height="200px"+ onChange={handleClickhouseQueryChange}+ value={queryData.clickHouseQuery}+ // options={options}+ />+ ) : queryCategory === 2 ? (+ <PromQLQueryBuilder+ query={queryData.promQL.query}+ onQueryChange={(value) => handlePromQLQueryChange({ query: value })}+ legend={queryData.promQL.legend}+ onLegendChange={(value) => handlePromQLQueryChange({ legend: value })}+ />+ ) : null}+ </QueryBuilderWrapper>+ )}+ </QueryWrapper>+ );+}++interface QueryBuilderProps {+ queryCategory: TQueryCategories;+ name: string;+}+export default QueryBuilder;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/promQL/index.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/promQL/index.tsxnew file mode 100644index 0000000000..58d8685a15--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/promQL/index.tsx@@ -0,0 +1,67 @@+import { PlusOutlined } from '@ant-design/icons';+import { PromQLQueryTemplate } from 'constants/dashboard';+import GetQueryName from 'lib/query/GetQueryName';+import React from 'react';++import { WIDGET_PROMQL_QUERY_KEY_NAME } from '../../constants';+import { QueryButton } from '../../styles';+import PromQLQueryBuilder from './query';++function PromQLQueryContainer({+ queryData,+ updateQueryData,+ promQLQueries,+ onQueryChange,+ onQueryAdd,+}): JSX.Element | null {+ const handlePromQLQueryChange = ({+ queryIndex,+ query,+ legend,+ toggleDisable,+ toggleDelete,+ }): void => {+ const allQueries = queryData[WIDGET_PROMQL_QUERY_KEY_NAME];+ const currentIndexQuery = allQueries[queryIndex];+ if (query) currentIndexQuery.query = query;+ if (legend) currentIndexQuery.legend = legend;++ if (toggleDisable) {+ currentIndexQuery.disabled = !currentIndexQuery.disabled;+ }+ if (toggleDelete) {+ allQueries.splice(queryIndex, 1);+ }+ updateQueryData({ updatedQuery: { ...queryData } });+ };+ const addQueryHandler = (): void => {+ queryData[WIDGET_PROMQL_QUERY_KEY_NAME].push({+ name: GetQueryName(queryData[WIDGET_PROMQL_QUERY_KEY_NAME]),+ ...PromQLQueryTemplate,+ });+ updateQueryData({ updatedQuery: { ...queryData } });+ };++ if (!promQLQueries) {+ return null;+ }+ return (+ <>+ {promQLQueries.map(+ (q, idx): JSX.Element => (+ <PromQLQueryBuilder+ key={q.name}+ queryIndex={idx}+ queryData={q}+ handleQueryChange={handlePromQLQueryChange}+ />+ ),+ )}+ <QueryButton onClick={addQueryHandler} icon={<PlusOutlined />}>+ Query+ </QueryButton>+ </>+ );+}++export default PromQLQueryContainer;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/promQL/query.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/promQL/query.tsxnew file mode 100644index 0000000000..26c089b20b--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/promQL/query.tsx@@ -0,0 +1,45 @@+import { Input } from 'antd';+import React from 'react';++import QueryHeader from '../QueryHeader';++function PromQLQueryBuilder({+ queryData,+ queryIndex,+ handleQueryChange,+}): JSX.Element {+ return (+ <QueryHeader+ name={queryData.name}+ disabled={queryData.disabled}+ onDisable={(): void =>+ handleQueryChange({ queryIndex, toggleDisable: true })+ }+ onDelete={(): void => {+ handleQueryChange({ queryIndex, toggleDelete: true });+ }}+ >+ <Input+ onChange={(event): void =>+ handleQueryChange({ queryIndex, query: event.target.value })+ }+ size="middle"+ defaultValue={queryData.query}+ addonBefore="PromQL Query"+ style={{ marginBottom: '0.5rem' }}+ />++ <Input+ onChange={(event): void =>+ handleQueryChange({ queryIndex, legend: event.target.value })+ }+ size="middle"+ defaultValue={queryData.legend}+ addonBefore="Legend Format"+ style={{ marginBottom: '0.5rem' }}+ />+ </QueryHeader>+ );+}++export default PromQLQueryBuilder;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/MetricTagKey.machine.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/MetricTagKey.machine.tsnew file mode 100644index 0000000000..f082f4091f--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/MetricTagKey.machine.ts@@ -0,0 +1,61 @@+import { createMachine } from 'xstate';++export const ResourceAttributesFilterMachine =+ /** @xstate-layout N4IgpgJg5mDOIC5QBECGsAWAjA9qgThAAQDKYBAxhkQIIB2xAYgJYA2ALmPgHQAqqUANJgAngGIAcgFEAGr0SgADjljN2zHHQUgAHogAcAFgAM3AOz6ATAEYAzJdsA2Y4cOWAnABoQIxAFpDR2tuQ319AFYTcKdbFycAX3jvNExcAmIySmp6JjZOHn4hUTFNACFWAFd8bWVVdU1tPQQzY1MXY2tDdzNHM3dHd0NvXwR7biMTa313S0i+63DE5PRsPEJScnwqWgYiFg4uPgFhcQAlKRIpeSQQWrUNLRumx3Czbg8TR0sbS31jfUcw38fW47gBHmm4XCVms3SWIBSq3SGyyO1yBx4AHlFFxUOwcPhJLJrkoVPcGk9ENYFuF3i5YR0wtEHECEAEgiEmV8zH1DLYzHZ4Yi0utMltsrt9vluNjcfjCWVKtUbnd6o9QE1rMYBtxbGFvsZ3NrZj1WdYOfotUZLX0XEFHEKViKMpttjk9nlDrL8HiCWJzpcSbcyWrGoh3NCQj0zK53P1ph1WeFLLqnJZ2s5vmZLA6kginWsXaj3VLDoUAGqoSpgEp0cpVGohh5hhDWDy0sz8zruakzamWVm-Qyg362V5-AZOayO1KFlHitEejFHKCV6v+i5XRt1ZuU1s52zjNOOaZfdOWIY+RDZ0Hc6ZmKEXqyLPPCudit2Sz08ACSEFYNbSHI27kuquiIOEjiONwjJgrM3RWJYZisgEIJgnYPTmuEdi2OaiR5nQOAQHA2hvsiH4Sui0qFCcIGhnuLSmP0YJuJ2xjJsmKELG8XZTK0tjdHG06vgW5GupRS7St6vrKqSO4UhqVL8TBWp8o4eqdl0A5Xmy3G6gK56-B4uERDOSKiuJi6lgUAhrhUYB0buimtrEKZBDYrxaS0OZca8+ltheybOI4hivGZzrzp+VGHH+AGOQp4EIHy+ghNYnawtG4TsbYvk8QKfHGAJfQ9uF76WSW37xWBTSGJ0qXpd0vRZdEKGPqC2YeO2-zfO4+HxEAA */+ createMachine({+ tsTypes: {} as import('./MetricTagKey.machine.typegen').Typegen0,+ initial: 'Idle',+ states: {+ TagKey: {+ on: {+ NEXT: {+ actions: 'onSelectOperator',+ target: 'Operator',+ },+ onBlur: {+ actions: 'onBlurPurge',+ target: 'Idle',+ },+ RESET: {+ target: 'Idle',+ },+ },+ },+ Operator: {+ on: {+ NEXT: {+ actions: 'onSelectTagValue',+ target: 'TagValue',+ },+ // onBlur: {+ // actions: 'onBlurPurge',+ // target: 'Idle',+ // },+ RESET: {+ target: 'Idle',+ },+ },+ },+ TagValue: {+ on: {+ onBlur: {+ actions: ['onValidateQuery'],+ // target: 'Idle',+ },+ RESET: {+ target: 'Idle',+ },+ },+ },+ Idle: {+ on: {+ NEXT: {+ actions: 'onSelectTagKey',+ description: 'Select Category',+ target: 'TagKey',+ },+ },+ },+ },+ id: 'Dashboard Search And Filter',+ });diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/MetricTagKey.machine.typegen.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/MetricTagKey.machine.typegen.tsnew file mode 100644index 0000000000..e7f7ee3de7--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/MetricTagKey.machine.typegen.ts@@ -0,0 +1,32 @@+// This file was automatically generated. Edits will be overwritten++export interface Typegen0 {+ '@@xstate/typegen': true;+ eventsCausingActions: {+ onSelectOperator: 'NEXT';+ onBlurPurge: 'onBlur';+ onSelectTagValue: 'NEXT';+ onValidateQuery: 'onBlur';+ onSelectTagKey: 'NEXT';+ };+ internalEvents: {+ 'xstate.init': { type: 'xstate.init' };+ };+ invokeSrcNameMap: {};+ missingImplementations: {+ actions:+ | 'onSelectOperator'+ | 'onBlurPurge'+ | 'onSelectTagValue'+ | 'onValidateQuery'+ | 'onSelectTagKey';+ services: never;+ guards: never;+ delays: never;+ };+ eventsCausingServices: {};+ eventsCausingGuards: {};+ eventsCausingDelays: {};+ matchesStates: 'TagKey' | 'Operator' | 'TagValue' | 'Idle';+ tags: never;+}diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/QueryChip.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/QueryChip.tsxnew file mode 100644index 0000000000..72da49ae49--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/QueryChip.tsx@@ -0,0 +1,31 @@+import React from 'react';++import { QueryChipContainer, QueryChipItem } from './styles';+import { IMetricBuilderTagKeyQuery } from './types';++interface IQueryChipProps {+ queryData: IMetricBuilderTagKeyQuery;+ onClose: (id: string) => void;+ disabled: boolean;+}++export default function QueryChip({+ queryData,+ onClose,+ disabled,+}: IQueryChipProps): JSX.Element {+ return (+ <QueryChipContainer>+ <QueryChipItem>{queryData.key}</QueryChipItem>+ <QueryChipItem>{queryData.op}</QueryChipItem>+ <QueryChipItem+ closable={!disabled}+ onClose={(): void => {+ if (!disabled) onClose(queryData.id);+ }}+ >+ {queryData.value.join(', ')}+ </QueryChipItem>+ </QueryChipContainer>+ );+}diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/index.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/index.tsxnew file mode 100644index 0000000000..ee58974549--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/index.tsx@@ -0,0 +1,211 @@+import { CloseCircleFilled } from '@ant-design/icons';+import { useMachine } from '@xstate/react';+import { Button, Select, Spin } from 'antd';+import { map } from 'lodash-es';+import React, { useCallback, useEffect, useState } from 'react';+import { useSelector } from 'react-redux';+import { AppState } from 'store/reducers';+import AppReducer from 'types/reducer/app';+import { v4 as uuid } from 'uuid';++import { ResourceAttributesFilterMachine } from './MetricTagKey.machine';+import QueryChip from './QueryChip';+import { QueryChipItem, SearchContainer } from './styles';+import { IMetricBuilderTagKeyQuery, IOption } from './types';+import {+ createQuery,+ GetTagKeys,+ GetTagValues,+ OperatorSchema,+ SingleValueOperators,+} from './utils';++function MetricTagKeyFilter({+ metricName,+ onSetQuery,+ selectedTagFilters: selectedTagQueries,+}): JSX.Element | null {+ const { isDarkMode } = useSelector<AppState, AppReducer>((state) => state.app);+ const [loading, setLoading] = useState(true);+ const [selectedValues, setSelectedValues] = useState<string[]>([]);+ const [staging, setStaging] = useState<string[]>([]);+ const [queries, setQueries] = useState<IMetricBuilderTagKeyQuery[]>([]);+ const [optionsData, setOptionsData] = useState<{+ mode: undefined | 'tags' | 'multiple';+ options: IOption[];+ }>({+ mode: undefined,+ options: [],+ });++ const dispatchQueries = (+ updatedQueries: IMetricBuilderTagKeyQuery[],+ ): void => {+ onSetQuery(updatedQueries);+ setQueries(updatedQueries);+ };+ const handleLoading = (isLoading: boolean): void => {+ setLoading(isLoading);+ if (isLoading) {+ setOptionsData({ mode: undefined, options: [] });+ }+ };+ const [state, send] = useMachine(ResourceAttributesFilterMachine, {+ actions: {+ onSelectTagKey: () => {+ handleLoading(true);+ GetTagKeys(metricName)+ .then((tagKeys) => setOptionsData({ options: tagKeys, mode: undefined }))+ .finally(() => {+ handleLoading(false);+ });+ },+ onSelectOperator: () => {+ setOptionsData({ options: OperatorSchema, mode: undefined });+ },+ onSelectTagValue: () => {+ handleLoading(true);++ GetTagValues(staging[0], metricName)+ .then((tagValuesOptions) =>+ setOptionsData({ options: tagValuesOptions, mode: 'tags' }),+ )+ .finally(() => {+ handleLoading(false);+ });+ },+ onBlurPurge: () => {+ setSelectedValues([]);+ setStaging([]);+ },+ onValidateQuery: (): void => {+ if (staging.length < 2 || selectedValues.length === 0) {+ return;+ }++ const generatedQuery = createQuery([...staging, selectedValues]);++ if (generatedQuery) {+ dispatchQueries([...queries, generatedQuery]);+ setSelectedValues([]);+ setStaging([]);+ send('RESET');+ }+ },+ },+ });++ useEffect(() => {+ setQueries(selectedTagQueries);+ }, [selectedTagQueries]);++ const handleFocus = (): void => {+ if (state.value === 'Idle') {+ send('NEXT');+ }+ };++ const handleBlur = useCallback((): void => {+ send('onBlur');+ }, [send]);++ useEffect(() => {+ handleBlur();+ }, [handleBlur, metricName]);++ const handleChange = (value: never): void => {+ if (!optionsData.mode) {+ setStaging((prevStaging) => [...prevStaging, value]);+ setSelectedValues([]);+ send('NEXT');+ return;+ }+ if (+ state.value === 'TagValue' &&+ SingleValueOperators.includes(staging[staging.length - 1])+ ) {+ setSelectedValues([value[value.length - 1]]);+ return;+ }++ setSelectedValues([...value]);+ };++ const handleClose = (id: string): void => {+ dispatchQueries(queries.filter((queryData) => queryData.id !== id));+ };++ const handleClearAll = (): void => {+ send('RESET');+ dispatchQueries([]);+ setStaging([]);+ setSelectedValues([]);+ };++ const disabledOrEmpty = !!(+ queries.length ||+ staging.length ||+ selectedValues.length+ );++ return (+ <SearchContainer isDarkMode={isDarkMode}>+ <div style={{ display: 'inline-flex', flexWrap: 'wrap' }}>+ {queries.length > 0 &&+ map(+ queries,+ (query): JSX.Element => {+ return (+ <QueryChip key={query.id} queryData={query} onClose={handleClose} />+ );+ },+ )}+ </div>+ <div>+ {map(staging, (item, idx) => {+ return <QueryChipItem key={uuid()}>{item}</QueryChipItem>;+ })}+ </div>++ <div style={{ display: 'flex', width: '100%' }}>+ <Select+ disabled={!metricName}+ placeholder={`Select ${+ state.value === 'Idle' ? 'Tag Key Pair' : state.value+ }`}+ onChange={handleChange}+ bordered={false}+ value={selectedValues as never}+ style={{ flex: 1 }}+ options={optionsData.options}+ mode={optionsData?.mode}+ showArrow={false}+ onFocus={handleFocus}+ onBlur={handleBlur}+ notFoundContent={+ loading ? (+ <span>+ <Spin size="small" /> Loading...{' '}+ </span>+ ) : (+ <span>+ No resource attributes available to filter. Please refer docs to send+ attributes.+ </span>+ )+ }+ />++ {queries.length || staging.length || selectedValues.length ? (+ <Button+ onClick={handleClearAll}+ icon={<CloseCircleFilled />}+ type="text"+ />+ ) : null}+ </div>+ </SearchContainer>+ );+}++export default MetricTagKeyFilter;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/styles.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/styles.tsnew file mode 100644index 0000000000..035dca4dd7--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/styles.ts@@ -0,0 +1,30 @@+import { grey } from '@ant-design/colors';+import { Tag } from 'antd';+import styled from 'styled-components';++export const SearchContainer = styled.div<{+ isDarkMode: boolean;+ disabled: boolean;+}>`+ background: ${({ isDarkMode }): string => (isDarkMode ? '#000' : '#fff')};+ flex: 1;+ display: flex;+ flex-direction: column;+ padding: 0.2rem;+ border: 1px solid #ccc5;+ ${({ disabled }): string => (disabled ? `cursor: not-allowed;` : '')}+`;+export const QueryChipContainer = styled.span`+ display: flex;+ align-items: center;+ margin-right: 0.5rem;+ &:hover {+ & > * {+ background: ${grey.primary}44;+ }+ }+`;++export const QueryChipItem = styled(Tag)`+ margin-right: 0.1rem;+`;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/types.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/types.tsnew file mode 100644index 0000000000..4eb8bb719c--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/types.ts@@ -0,0 +1,11 @@+export interface IOption {+ label: string;+ value: string;+}++export interface IMetricBuilderTagKeyQuery {+ id: string;+ tagKey: string;+ operator: string;+ tagValue: string[];+}diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/utils.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/utils.tsnew file mode 100644index 0000000000..685d05d095--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/MetricTagKeyFilter/utils.ts@@ -0,0 +1,55 @@+import {+ getResourceAttributesTagKeys,+ getResourceAttributesTagValues,+} from 'api/metrics/getResourceAttributes';+import { v4 as uuid } from 'uuid';++import { TagKeyOperator } from '../../Options';+import { IMetricBuilderTagKeyQuery, IOption } from './types';++export const OperatorSchema: IOption[] = TagKeyOperator;++export const GetTagKeys = async (metricName: string): Promise<IOption[]> => {+ const { payload } = await getResourceAttributesTagKeys({ metricName });+ if (!payload || !payload?.data) {+ return [];+ }+ return payload.data.map((tagKey: string) => ({+ label: tagKey,+ value: tagKey,+ }));+};++export const GetTagValues = async (+ tagKey: string,+ metricName: string,+): Promise<IOption[]> => {+ const { payload } = await getResourceAttributesTagValues({+ tagKey,+ metricName,+ });++ if (!payload || !payload?.data) {+ return [];+ }+ return payload.data.map((tagValue: string) => ({+ label: tagValue,+ value: tagValue,+ }));+};++export const createQuery = (+ selectedItems: Array<string | string[]> = [],+): IMetricBuilderTagKeyQuery | null => {+ if (selectedItems.length === 3) {+ return {+ id: uuid().slice(0, 8),+ key: selectedItems[0] as string,+ op: selectedItems[1] as string,+ value: selectedItems[2] as string[],+ };+ }+ return null;+};++export const SingleValueOperators = ['LIKE', 'NLIKE'];diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/formula.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/formula.tsxnew file mode 100644index 0000000000..bc47ddf33c--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/formula.tsx@@ -0,0 +1,37 @@+import { Input } from 'antd';+import React from 'react';++import QueryHeader from '../QueryHeader';++const { TextArea } = Input;++function MetricsBuilderFormula({+ formulaData,+ formulaIndex,+ handleFormulaChange,+}): JSX.Element {+ return (+ <QueryHeader+ name={formulaData.name}+ disabled={formulaData.disabled}+ onDisable={(): void =>+ handleFormulaChange({ formulaIndex, toggleDisable: true })+ }+ onDelete={(): void => {+ handleFormulaChange({ formulaIndex, toggleDelete: true });+ }}+ >+ <TextArea+ onChange={(event): void =>+ handleFormulaChange({ formulaIndex, expression: event.target.value })+ }+ size="middle"+ defaultValue={formulaData.expression}+ style={{ marginBottom: '0.5rem' }}+ rows={2}+ />+ </QueryHeader>+ );+}++export default MetricsBuilderFormula;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/index.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/index.tsxnew file mode 100644index 0000000000..6a4b812c62--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/index.tsx@@ -0,0 +1,168 @@+import { PlusOutlined } from '@ant-design/icons';+import { notification } from 'antd';+import {+ QueryBuilderFormulaTemplate,+ QueryBuilderQueryTemplate,+} from 'constants/dashboard';+import GetFormulaName from 'lib/query/GetFormulaName';+import GetQueryName from 'lib/query/GetQueryName';+import React from 'react';++import {+ WIDGET_QUERY_BUILDER_FORMULA_KEY_NAME,+ WIDGET_QUERY_BUILDER_QUERY_KEY_NAME,+} from '../../constants';+import { QueryButton } from '../../styles';+import MetricsBuilderFormula from './formula';+import MetricsBuilder from './query';+import { canCreateQueryAndFormula } from './utils';++function QueryBuilderQueryContainer({+ queryData,+ updateQueryData,+ metricsBuilderQueries,+ selectedGraph,+}): JSX.Element | null {+ const handleQueryBuilderQueryChange = ({+ queryIndex,+ aggregateFunction,+ metricName,+ tagFilters,+ groupBy,+ legend,+ toggleDisable,+ toggleDelete,+ reduceTo,+ }): void => {+ const allQueries =+ queryData[WIDGET_QUERY_BUILDER_QUERY_KEY_NAME].queryBuilder;+ const currentIndexQuery = allQueries[queryIndex];+ if (aggregateFunction) {+ currentIndexQuery.aggregateOperator = aggregateFunction;+ }++ if (metricName) {+ currentIndexQuery.metricName = metricName;+ }++ if (tagFilters) {+ currentIndexQuery.tagFilters.items = tagFilters;+ }++ if (groupBy) {+ currentIndexQuery.groupBy = groupBy;+ }++ if (reduceTo) {+ currentIndexQuery.reduceTo = reduceTo;+ }++ if (legend !== undefined) {+ currentIndexQuery.legend = legend;+ }+ if (toggleDisable) {+ currentIndexQuery.disabled = !currentIndexQuery.disabled;+ }+ if (toggleDelete) {+ allQueries.splice(queryIndex, 1);+ }+ updateQueryData({ updatedQuery: { ...queryData } });+ };+ const handleQueryBuilderFormulaChange = ({+ formulaIndex,+ expression,+ toggleDisable,+ toggleDelete,+ }): void => {+ const allFormulas =+ queryData[WIDGET_QUERY_BUILDER_QUERY_KEY_NAME][+ WIDGET_QUERY_BUILDER_FORMULA_KEY_NAME+ ];+ const currentIndexFormula = allFormulas[formulaIndex];++ if (expression) {+ currentIndexFormula.expression = expression;+ }++ if (toggleDisable) {+ currentIndexFormula.disabled = !currentIndexFormula.disabled;+ }++ if (toggleDelete) {+ allFormulas.splice(formulaIndex, 1);+ }+ updateQueryData({ updatedQuery: { ...queryData } });+ };+ const addQueryHandler = (): void => {+ if (!canCreateQueryAndFormula(queryData)) {+ notification.error({+ message:+ 'Unable to create query. You can create at max 10 queries and formulae.',+ });+ return;+ }+ queryData[WIDGET_QUERY_BUILDER_QUERY_KEY_NAME].queryBuilder.push({+ name: GetQueryName(+ queryData[WIDGET_QUERY_BUILDER_QUERY_KEY_NAME].queryBuilder,+ ),+ ...QueryBuilderQueryTemplate,+ });+ updateQueryData({ updatedQuery: { ...queryData } });+ };++ const addFormulaHandler = (): void => {+ if (!canCreateQueryAndFormula(queryData)) {+ notification.error({+ message:+ 'Unable to create formula. You can create at max 10 queries and formulae.',+ });+ return;+ }+ queryData[WIDGET_QUERY_BUILDER_QUERY_KEY_NAME][+ WIDGET_QUERY_BUILDER_FORMULA_KEY_NAME+ ].push({+ name: GetFormulaName(+ queryData[WIDGET_QUERY_BUILDER_QUERY_KEY_NAME][+ WIDGET_QUERY_BUILDER_FORMULA_KEY_NAME+ ],+ ),+ ...QueryBuilderFormulaTemplate,+ });+ updateQueryData({ updatedQuery: { ...queryData } });+ };++ if (!metricsBuilderQueries) {+ return null;+ }+ return (+ <>+ {metricsBuilderQueries.queryBuilder.map((q, idx) => (+ <MetricsBuilder+ key={q.name}+ queryIndex={idx}+ queryData={q}+ handleQueryChange={handleQueryBuilderQueryChange}+ selectedGraph={selectedGraph}+ />+ ))}+ <QueryButton onClick={addQueryHandler} icon={<PlusOutlined />}>+ Query+ </QueryButton>+ <div style={{ marginTop: '1rem' }}>+ {metricsBuilderQueries.formulas.map((f, idx) => (+ <MetricsBuilderFormula+ key={f.name}+ formulaIndex={idx}+ formulaData={f}+ handleFormulaChange={handleQueryBuilderFormulaChange}+ />+ ))}+ <QueryButton onClick={addFormulaHandler} icon={<PlusOutlined />}>+ Formula+ </QueryButton>+ </div>+ </>+ );+}++export default QueryBuilderQueryContainer;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/query.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/query.tsxnew file mode 100644index 0000000000..d953ab9dae--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/query.tsx@@ -0,0 +1,200 @@+import { AutoComplete, Col, Input, Row, Select, Spin } from 'antd';+import { getMetricName } from 'api/metrics/getMetricName';+import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';+import React, { useEffect, useState } from 'react';+import { EReduceOperator } from 'types/common/dashboard';++import { TQueryCategories } from '../../types';+import { AggregateFunctions } from '../Options';+import QueryHeader from '../QueryHeader';+import MetricTagKeyFilter from './MetricTagKeyFilter';+import { GetTagKeys } from './MetricTagKeyFilter/utils';++const { Option } = Select;+function MetricsBuilder({+ queryData,+ queryIndex,+ handleQueryChange,+ selectedGraph,+}: QueryBuilderProps): JSX.Element {+ const [groupByOptions, setGroupByOptions] = useState([]);+ const [metricName, setMetricName] = useState(queryData.metricName);++ const [metricNameList, setMetricNameList] = useState([]);+ const [metricNameLoading, setMetricNameLoading] = useState(false);++ const handleMetricNameSelect = (e): void => {+ handleQueryChange({ queryIndex, metricName: e });+ setMetricName(e);+ };++ const handleMetricNameSearch = async (searchQuery = ''): Promise<void> => {+ handleMetricNameSelect(searchQuery);+ setMetricNameList([]);+ setMetricNameLoading(true);+ const { payload } = await getMetricName(searchQuery);+ setMetricNameLoading(false);+ if (!payload || !payload.data) {+ return;+ }+ setMetricNameList(payload.data);+ };+ const [aggregateFunctionList, setAggregateFunctionList] = useState(+ AggregateFunctions,+ );+ const handleAggregateFunctionsSearch = (searchQuery = ''): void => {+ setAggregateFunctionList(+ AggregateFunctions.filter(({ label }) =>+ label.includes(searchQuery.toUpperCase()),+ ) || [],+ );+ };++ useEffect(() => {+ GetTagKeys(metricName).then((tagKeys) => {+ setGroupByOptions(tagKeys);+ });+ }, [metricName]);++ return (+ <QueryHeader+ name={queryData.name}+ disabled={queryData.disabled}+ onDisable={(): void =>+ handleQueryChange({ queryIndex, toggleDisable: true })+ }+ onDelete={(): void => {+ handleQueryChange({ queryIndex, toggleDelete: true });+ }}+ >+ <div style={{ display: 'flex', flexDirection: 'column', padding: '0.5rem' }}>+ <div>+ <Select+ onChange={(e): void =>+ handleQueryChange({ queryIndex, aggregateFunction: e })+ }+ defaultValue={queryData.aggregateOperator || AggregateFunctions[0]}+ style={{ minWidth: 150 }}+ options={aggregateFunctionList}+ showSearch+ onSearch={handleAggregateFunctionsSearch}+ filterOption={false}+ />+ </div>+ <Row style={{ gap: '3%', margin: '0.5rem 0' }}>+ <Row style={{ flex: 2, gap: '3%' }}>+ <Select+ defaultValue="metrics"+ showArrow={false}+ dropdownStyle={{ display: 'none' }}+ >+ <Option value="metrics">Metrics</Option>+ </Select>++ <AutoComplete+ showSearch+ placeholder="Metric Name (Start typing to get suggestions)"+ style={{ flex: 1, minWidth: 200 }}+ showArrow={false}+ filterOption={false}+ onSearch={handleMetricNameSearch}+ notFoundContent={metricNameLoading ? <Spin size="small" /> : null}+ options={metricNameList.map((option) => ({+ label: option,+ value: option,+ }))}+ defaultValue={queryData.metricName}+ value={metricName}+ onSelect={handleMetricNameSelect}+ />+ </Row>+ <Col style={{ flex: 3 }}>+ <Row style={{ gap: '3%', marginBottom: '1rem' }}>+ <Select+ defaultValue="WHERE"+ showArrow={false}+ dropdownStyle={{ display: 'none' }}+ >+ <Option value="WHERE">WHERE</Option>+ </Select>+ <MetricTagKeyFilter+ metricName={metricName}+ selectedTagFilters={queryData.tagFilters.items}+ onSetQuery={(updatedTagFilters): void =>+ handleQueryChange({ queryIndex, tagFilters: updatedTagFilters })+ }+ />+ </Row>+ <Row style={{ gap: '3%', marginBottom: '1rem' }}>+ {selectedGraph === 'TIME_SERIES' ? (+ <>+ {' '}+ <Select+ defaultValue="GROUP BY"+ showArrow={false}+ dropdownStyle={{ display: 'none' }}+ >+ <Option value="GROUP BY">GROUP BY</Option>+ </Select>+ <Select+ mode="multiple"+ showSearch+ style={{ flex: 1 }}+ defaultActiveFirstOption={false}+ filterOption={false}+ notFoundContent={metricNameLoading ? <Spin size="small" /> : null}+ options={groupByOptions}+ defaultValue={queryData.groupBy}+ onChange={(e): void => {+ handleQueryChange({ queryIndex, groupBy: e });+ }}+ />+ </>+ ) : (+ <>+ <Select+ defaultValue="REDUCE TO"+ showArrow={false}+ dropdownStyle={{ display: 'none' }}+ >+ <Option value="GROUP BY">REDUCE TO</Option>+ </Select>+ <Select+ placeholder="Latest of values in timeframe"+ style={{ flex: 1 }}+ options={Object.keys(EReduceOperator)+ .filter((op) => !(parseInt(op, 10) >= 0))+ .map((op) => ({+ label: op,+ value: EReduceOperator[op],+ }))}+ defaultValue={EReduceOperator[queryData.reduceTo]}+ onChange={(e): void => {+ handleQueryChange({ queryIndex, reduceTo: e });+ }}+ />+ </>+ )}+ </Row>+ </Col>+ </Row>+ <Row style={{ margin: '0.5rem 0' }}>+ <Input+ onChange={(e): void => {+ handleQueryChange({ queryIndex, legend: e.target.value });+ }}+ size="middle"+ defaultValue={queryData.legend}+ addonBefore="Legend Format"+ />+ </Row>+ </div>+ </QueryHeader>+ );+}++interface QueryBuilderProps {+ selectedGraph: GRAPH_TYPES;+ queryCategory: TQueryCategories;+}+export default MetricsBuilder;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/utils.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/utils.tsnew file mode 100644index 0000000000..977d194c9b--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/QueryBuilder/queryBuilder/utils.ts@@ -0,0 +1,16 @@+import {+ WIDGET_QUERY_BUILDER_FORMULA_KEY_NAME,+ WIDGET_QUERY_BUILDER_QUERY_KEY_NAME,+} from '../../constants';++const QUERY_AND_FORMULA_LIMIT = 10;++export const canCreateQueryAndFormula = (query): boolean => {+ const queries = query[WIDGET_QUERY_BUILDER_QUERY_KEY_NAME].queryBuilder;+ const formulas =+ query[WIDGET_QUERY_BUILDER_QUERY_KEY_NAME][+ WIDGET_QUERY_BUILDER_FORMULA_KEY_NAME+ ];++ return queries.length + formulas.length < QUERY_AND_FORMULA_LIMIT;+};diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/TabHeader.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/TabHeader.tsxnew file mode 100644index 0000000000..c8067a873b--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/TabHeader.tsx@@ -0,0 +1,31 @@+import { Tooltip } from 'antd';+import React from 'react';++function TabHeader({ tabName, hasUnstagedChanges }): JSX.Element {+ return (+ <div+ style={{+ display: 'flex',+ gap: '0.5rem',+ justifyContent: 'center',+ alignItems: 'center',+ }}+ >+ {tabName}+ {hasUnstagedChanges && (+ <Tooltip title="Looks like you have un-staged changes. Make sure you click 'Stage & Run Query' if you want to save these changes.">+ <div+ style={{+ height: '0.6rem',+ width: '0.6rem',+ borderRadius: '1rem',+ background: 'orange',+ }}+ />+ </Tooltip>+ )}+ </div>+ );+}++export default TabHeader;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/constants.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/constants.tsnew file mode 100644index 0000000000..35e6cf5b63--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/constants.ts@@ -0,0 +1,17 @@+import { EQueryType } from 'types/common/dashboard';++import { EQueryTypeToQueryKeyMapping } from './types';++export const WIDGET_PROMQL_QUERY_KEY_NAME: string = EQueryTypeToQueryKeyMapping[+ EQueryType[EQueryType.PROM]+] as string;++export const WIDGET_CLICKHOUSE_QUERY_KEY_NAME: string = EQueryTypeToQueryKeyMapping[+ EQueryType[EQueryType.CLICKHOUSE]+] as string;++export const WIDGET_QUERY_BUILDER_QUERY_KEY_NAME: string = EQueryTypeToQueryKeyMapping[+ EQueryType[EQueryType.QUERY_BUILDER]+] as string;++export const WIDGET_QUERY_BUILDER_FORMULA_KEY_NAME: string = 'formulas' as string;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsxindex c0ad837b9c..fb1cf331c6 100644--- a/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx@@ -1,20 +1,57 @@-import { PlusOutlined } from '@ant-design/icons';+import { Button, Tabs } from 'antd';+import TextToolTip from 'components/TextToolTip';+import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';import { timePreferance } from 'container/NewWidget/RightContainer/timeItems';-import React, { useCallback, useMemo } from 'react';+import { cloneDeep, isEqual } from 'lodash-es';+import React, { useCallback, useEffect, useMemo, useState } from 'react';import { connect, useSelector } from 'react-redux';import { useLocation } from 'react-router-dom';import { bindActionCreators, Dispatch } from 'redux';import { ThunkDispatch } from 'redux-thunk';import { CreateQuery, CreateQueryProps } from 'store/actions';+import {+ GetQueryResults,+ GetQueryResultsProps,+} from 'store/actions/dashboard/getQueryResults';+import {+ UpdateQuery,+ UpdateQueryProps,+} from 'store/actions/dashboard/updateQuery';+import {+ UpdateQueryType,+ UpdateQueryTypeProps,+} from 'store/actions/dashboard/updateQueryType';import { AppState } from 'store/reducers';import AppActions from 'types/actions';import { Widgets } from 'types/api/dashboard/getAll';+import { EQueryType } from 'types/common/dashboard';import DashboardReducer from 'types/reducer/dashboards';+import { v4 as uuid } from 'uuid';-import Query from './Query';-import { QueryButton } from './styles';+import {+ WIDGET_CLICKHOUSE_QUERY_KEY_NAME,+ WIDGET_PROMQL_QUERY_KEY_NAME,+ WIDGET_QUERY_BUILDER_QUERY_KEY_NAME,+} from './constants';+import ClickHouseQueryContainer from './QueryBuilder/clickHouse';+import PromQLQueryContainer from './QueryBuilder/promQL';+import QueryBuilderQueryContainer from './QueryBuilder/queryBuilder';+import TabHeader from './TabHeader';+import { getQueryKey } from './utils/getQueryKey';+import { showUnstagedStashConfirmBox } from './utils/userSettings';-function QuerySection({ selectedTime, createQuery }: QueryProps): JSX.Element {+const { TabPane } = Tabs;+function QuerySection({+ handleUnstagedChanges,+ updateQuery,+ selectedGraph,+}: QueryProps): JSX.Element {+ const [localQueryChanges, setLocalQueryChanges] = useState({});+ const [rctTabKey, setRctTabKey] = useState({+ QUERY_BUILDER: uuid(),+ CLICKHOUSE: uuid(),+ PROMQL: uuid(),+ });const { dashboards } = useSelector<AppState, DashboardReducer>((state) => state.dashboards,);@@ -32,50 +69,256 @@ function QuerySection({ selectedTime, createQuery }: QueryProps): JSX.Element {}, [widgets, urlQuery]);const selectedWidget = getWidget() as Widgets;+ const [queryCategory, setQueryCategory] = useState<EQueryType>(+ selectedWidget.query.queryType,+ );const { query = [] } = selectedWidget || {};+ useEffect(() => {+ setLocalQueryChanges(cloneDeep(query));+ }, [query]);+ const queryOnClickHandler = () => {+ setLocalQueryChanges([+ ...localQueryChanges,+ // {+ // name: GetQueryName(localQueryChanges),+ // disabled: false,- const queryOnClickHandler = useCallback(() => {- const widgetId = urlQuery.get('widgetId');+ // promQL: {+ // query: '',+ // legend: '',+ // },+ // clickHouseQuery: '',+ // queryBuilder: {+ // metricName: null,+ // aggregateOperator: null,+ // tagFilters: {+ // op: 'AND',+ // items: [],+ // },+ // groupBy: [],+ // },+ // },+ ]);+ };++ const queryDiff = (queryA, queryB, queryCategory) => {+ const keyOfConcern = getQueryKey(queryCategory);+ return !isEqual(queryA[keyOfConcern], queryB[keyOfConcern]);+ };++ useEffect(() => {+ handleUnstagedChanges(+ queryDiff(query, localQueryChanges, parseInt(queryCategory)),+ );+ }, [handleUnstagedChanges, localQueryChanges, query, queryCategory]);++ const purgeLocalChanges = () => {+ setLocalQueryChanges(query);+ };+ const regenRctKeys = () => {+ setRctTabKey((prevState) => {+ Object.keys(prevState).map((key) => {+ prevState[key] = uuid();+ });++ return cloneDeep(prevState);+ });+ };- createQuery({- widgetId: String(widgetId),+ const handleStageQuery = () => {+ updateQuery({+ updatedQuery: localQueryChanges,+ widgetId: urlQuery.get('widgetId'),+ yAxisUnit: selectedWidget.yAxisUnit,});- }, [createQuery, urlQuery]);+ };++ const handleQueryCategoryChange = (qCategory): void => {+ // If true, then it means that the user has made some changes and haven't staged them+ const unstagedChanges = queryDiff(+ query,+ localQueryChanges,+ parseInt(queryCategory),+ );++ if (unstagedChanges && showUnstagedStashConfirmBox()) {+ window.confirm(+ "You are trying to navigate to different tab with unstaged changes. Your current changes will be purged. Press 'Stage & Run Query' to stage them.",+ );+ return;+ }++ setQueryCategory(parseInt(qCategory));+ const newLocalQuery = {+ ...cloneDeep(query),+ queryType: parseInt(qCategory),+ };+ setLocalQueryChanges(newLocalQuery);+ regenRctKeys();+ updateQuery({+ updatedQuery: newLocalQuery,+ widgetId: urlQuery.get('widgetId'),+ yAxisUnit: selectedWidget.yAxisUnit,+ });+ };+ const handleLocalQueryUpdate = ({ updatedQuery }) => {+ setLocalQueryChanges(updatedQuery);+ };++ const handleDeleteQuery = ({ currentIndex }) => {+ setLocalQueryChanges((prevState) => {+ prevState.splice(currentIndex, 1);+ return [...prevState];+ });+ };return (<>- {query.map((e, index) => (- <Query- currentIndex={index}- selectedTime={selectedTime}- key={`${e.query} ${e.query.length}`}- preQuery={e.query}- preLegend={e.legend || ''}+ <div style={{ display: 'flex' }}>+ <Tabs+ type="card"+ style={{ width: '100%' }}+ defaultActiveKey={queryCategory.toString()}+ activeKey={queryCategory.toString()}+ onChange={handleQueryCategoryChange}+ tabBarExtraContent={+ <span style={{ display: 'flex', gap: '1rem', alignItems: 'center' }}>+ <TextToolTip+ {...{+ text: `This will temporarily save the current query and graph state. This will persist across tab change`,+ }}+ />+ <Button type="primary" onClick={handleStageQuery}>+ Stage & Run Query+ </Button>+ </span>+ }+ >+ <TabPane+ tab={+ <TabHeader+ tabName="Query Builder"+ hasUnstagedChanges={queryDiff(+ query,+ localQueryChanges,+ EQueryType.QUERY_BUILDER,+ )}+ />+ }+ key={EQueryType.QUERY_BUILDER.toString()}+ >+ <QueryBuilderQueryContainer+ key={rctTabKey.QUERY_BUILDER}+ queryData={localQueryChanges}+ updateQueryData={({ updatedQuery }) => {+ handleLocalQueryUpdate({ updatedQuery });+ }}+ metricsBuilderQueries={+ localQueryChanges[WIDGET_QUERY_BUILDER_QUERY_KEY_NAME]+ }+ selectedGraph={selectedGraph}+ />+ </TabPane>+ <TabPane+ tab={+ <TabHeader+ tabName="ClickHouse Query"+ hasUnstagedChanges={queryDiff(+ query,+ localQueryChanges,+ EQueryType.CLICKHOUSE,+ )}+ />+ }+ key={EQueryType.CLICKHOUSE.toString()}+ >+ <ClickHouseQueryContainer+ key={rctTabKey.CLICKHOUSE}+ queryData={localQueryChanges}+ updateQueryData={({ updatedQuery }) => {+ handleLocalQueryUpdate({ updatedQuery });+ }}+ clickHouseQueries={localQueryChanges[WIDGET_CLICKHOUSE_QUERY_KEY_NAME]}+ />+ </TabPane>+ <TabPane+ tab={+ <TabHeader+ tabName="PromQL"+ hasUnstagedChanges={queryDiff(+ query,+ localQueryChanges,+ EQueryType.PROM,+ )}+ />+ }+ key={EQueryType.PROM.toString()}+ >+ <PromQLQueryContainer+ key={rctTabKey.PROMQL}+ queryData={localQueryChanges}+ updateQueryData={({ updatedQuery }) => {+ handleLocalQueryUpdate({ updatedQuery });+ }}+ promQLQueries={localQueryChanges[WIDGET_PROMQL_QUERY_KEY_NAME]}+ />+ </TabPane>+ </Tabs>+ </div>+ {/* {localQueryChanges.map((e, index) => (+ // <Query+ // name={e.name}+ // currentIndex={index}+ // selectedTime={selectedTime}+ // key={JSON.stringify(e)}+ // queryInput={e}+ // updatedLocalQuery={handleLocalQueryUpdate}+ // queryCategory={queryCategory}+ // />+ <QueryBuilder+ key={`${JSON.stringify(e)}`}+ name={e.name}+ updateQueryData={(updatedQuery) =>+ handleLocalQueryUpdate({ currentIndex: index, updatedQuery })+ }+ onDelete={() => handleDeleteQuery({ currentIndex: index })}+ queryData={e}+ queryCategory={queryCategory}/>- ))}-- <QueryButton onClick={queryOnClickHandler} icon={<PlusOutlined />}>- Query- </QueryButton>+ ))} */}</>);}interface DispatchProps {- createQuery: ({- widgetId,- }: CreateQueryProps) => (dispatch: Dispatch<AppActions>) => void;+ // createQuery: ({+ // widgetId,+ // }: CreateQueryProps) => (dispatch: Dispatch<AppActions>) => void;+ updateQuery: (+ props: UpdateQueryProps,+ ) => (dispatch: Dispatch<AppActions>) => void;+ // getQueryResults: (+ // props: GetQueryResultsProps,+ // ) => (dispatch: Dispatch<AppActions>) => void;+ // updateQueryType: (+ // props: UpdateQueryTypeProps,+ // ) => (dispatch: Dispatch<AppActions>) => void;}const mapDispatchToProps = (dispatch: ThunkDispatch<unknown, unknown, AppActions>,): DispatchProps => ({- createQuery: bindActionCreators(CreateQuery, dispatch),+ // createQuery: bindActionCreators(CreateQuery, dispatch),+ updateQuery: bindActionCreators(UpdateQuery, dispatch),+ // getQueryResults: bindActionCreators(GetQueryResults, dispatch),+ // updateQueryType: bindActionCreators(UpdateQueryType, dispatch),});interface QueryProps extends DispatchProps {+ selectedGraph: GRAPH_TYPES;selectedTime: timePreferance;+ handleUnstagedChanges: (arg0: boolean) => void;}export default connect(null, mapDispatchToProps)(QuerySection);diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/styles.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/styles.tsindex 8efadde259..3a0d73e1ab 100644--- a/frontend/src/container/NewWidget/LeftContainer/QuerySection/styles.ts+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/styles.ts@@ -8,6 +8,7 @@ export const InputContainer = styled.div`export const Container = styled.div`margin-top: 1rem;display: flex;+ flex-direction: column;`;export const QueryButton = styled(Button)`@@ -18,11 +19,15 @@ export const QueryButton = styled(Button)``;export const QueryWrapper = styled.div`- width: 100%; // parent need to 100%+ width: 100%;+ margin: 1rem 0;+ padding: 1rem 0.5rem;+ display: flex;+ flex-direction: column;+`;- > div {- width: 95%; // each child is taking 95% of the parent- }+export const QueryBuilderWrapper = styled.div<{ isDarkMode: boolean }>`+ background: ${({ isDarkMode }): string => (isDarkMode ? '#000' : '#efefef')};`;export const ButtonContainer = styled.div`diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/types.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/types.tsnew file mode 100644index 0000000000..67993af292--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/types.ts@@ -0,0 +1,13 @@+export type TQueryCategories = 'query_builder' | 'clickhouse_query' | 'promql';++export enum EQueryCategories {+ query_builder = 0,+ clickhouse_query,+ promql,+}++export enum EQueryTypeToQueryKeyMapping {+ QUERY_BUILDER = 'metricsBuilder',+ CLICKHOUSE = 'clickHouse',+ PROM = 'promQL',+}diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/utils/getQueryKey.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/utils/getQueryKey.tsnew file mode 100644index 0000000000..e698edc4a0--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/utils/getQueryKey.ts@@ -0,0 +1,7 @@+import { EQueryType } from 'types/common/dashboard';++import { EQueryTypeToQueryKeyMapping } from '../types';++export const getQueryKey = (queryCategory): EQueryTypeToQueryKeyMapping => {+ return EQueryTypeToQueryKeyMapping[EQueryType[queryCategory] as unknown];+};diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/utils/userSettings.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/utils/userSettings.tsnew file mode 100644index 0000000000..f05671556b--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/utils/userSettings.ts@@ -0,0 +1,23 @@+import getLocalStorageApi from 'api/browser/localstorage/get';+import setLocalStorageApi from 'api/browser/localstorage/set';++const UNSTAGE_CONFIRM_BOX_SHOW_COUNT = 2;+const UNSTAGE_CONFIRM_BOX_KEY =+ 'DASHBOARD_METRICS_BUILDER_UNSTAGE_STASH_CONFIRM_SHOW_COUNT';++export const showUnstagedStashConfirmBox = (): boolean => {+ const showCountTillNow: number = parseInt(+ getLocalStorageApi(UNSTAGE_CONFIRM_BOX_KEY) || '',+ 10,+ );+ if (Number.isNaN(showCountTillNow)) {+ setLocalStorageApi(UNSTAGE_CONFIRM_BOX_KEY, '1');+ return true;+ }++ if (showCountTillNow >= UNSTAGE_CONFIRM_BOX_SHOW_COUNT) {+ return false;+ }+ setLocalStorageApi(UNSTAGE_CONFIRM_BOX_KEY, `${showCountTillNow + 1}`);+ return true;+};diff --git a/frontend/src/container/NewWidget/LeftContainer/QueryTypeTag.tsx b/frontend/src/container/NewWidget/LeftContainer/QueryTypeTag.tsxnew file mode 100644index 0000000000..6838e994de--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QueryTypeTag.tsx@@ -0,0 +1,35 @@+import React from 'react';+import { EQueryType } from 'types/common/dashboard';++import { Tag } from '../styles';++interface IQueryTypeTagProps {+ queryType: EQueryType;+}+function QueryTypeTag({ queryType }: IQueryTypeTagProps): JSX.Element {+ switch (queryType) {+ case EQueryType.QUERY_BUILDER:+ return (+ <span>+ <Tag color="geekblue">Query Builder</Tag>+ </span>+ );++ case EQueryType.CLICKHOUSE:+ return (+ <span>+ <Tag color="orange">ClickHouse Query</Tag>+ </span>+ );+ case EQueryType.PROM:+ return (+ <span>+ <Tag color="green">PromQL</Tag>+ </span>+ );+ default:+ return <span />;+ }+}++export default QueryTypeTag;diff --git a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/PlotTag.tsx b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/PlotTag.tsxnew file mode 100644index 0000000000..6b5666cd89--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/PlotTag.tsx@@ -0,0 +1,17 @@+import React from 'react';++import QueryTypeTag from '../QueryTypeTag';++function PlotTag({ queryType }): JSX.Element | null {+ if (queryType === undefined) {+ return null;+ }++ return (+ <div style={{ marginLeft: '2rem', position: 'absolute', top: '1rem' }}>+ Plotted using <QueryTypeTag queryType={queryType} />+ </div>+ );+}++export default PlotTag;diff --git a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsxindex 37bf188bb3..78a5a3b85c 100644--- a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx+++ b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx@@ -34,7 +34,15 @@ function WidgetGraph({const { queryData, title, opacity, isStacked } = selectedWidget;- if (queryData.data.length === 0) {+ if (queryData.error) {+ return (+ <NotFoundContainer>+ <Typography>{queryData.errorMessage}</Typography>+ </NotFoundContainer>+ );+ }++ if (queryData.data.length === 0 || queryData.data[0].queryData.length === 0) {return (<NotFoundContainer><Typography>No Data</Typography>diff --git a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/index.tsx b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/index.tsxindex 2fa28b7e1b..342599c49a 100644--- a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/index.tsx+++ b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/index.tsx@@ -8,6 +8,7 @@ import { AppState } from 'store/reducers';import DashboardReducer from 'types/reducer/dashboards';import { NewWidgetProps } from '../../index';+import PlotTag from './PlotTag';import { AlertIconContainer, Container, NotFoundContainer } from './styles';import WidgetGraphComponent from './WidgetGraph';@@ -35,9 +36,9 @@ function WidgetGraph({}const { queryData } = selectedWidget;-return (<Container>+ <PlotTag queryType={selectedWidget.query.queryType} />{queryData.error && (<AlertIconContainer color="red" title={queryData.errorMessage}><InfoCircleOutlined />diff --git a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/styles.ts b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/styles.tsindex b376f0d247..32a8c15f08 100644--- a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/styles.ts+++ b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/styles.ts@@ -7,8 +7,8 @@ export const Container = styled(Card)`}.ant-card-body {- padding: 0;- height: 55vh;+ padding: 1.5rem 0;+ height: 57vh;/* padding-bottom: 2rem; */}`;diff --git a/frontend/src/container/NewWidget/LeftContainer/index.tsx b/frontend/src/container/NewWidget/LeftContainer/index.tsxindex 33c1bcaeaa..9e02adcd68 100644--- a/frontend/src/container/NewWidget/LeftContainer/index.tsx+++ b/frontend/src/container/NewWidget/LeftContainer/index.tsx@@ -10,13 +10,17 @@ function LeftContainer({selectedGraph,selectedTime,yAxisUnit,+ handleUnstagedChanges,}: LeftContainerProps): JSX.Element {return (<><WidgetGraph selectedGraph={selectedGraph} yAxisUnit={yAxisUnit} />-<QueryContainer>- <QuerySection selectedTime={selectedTime} />+ <QuerySection+ selectedTime={selectedTime}+ handleUnstagedChanges={handleUnstagedChanges}+ selectedGraph={selectedGraph}+ /></QueryContainer></>);@@ -24,6 +28,7 @@ function LeftContainer({interface LeftContainerProps extends NewWidgetProps {selectedTime: timePreferance;+ handleUnstagedChanges: (arg0: boolean) => void;}export default memo(LeftContainer);diff --git a/frontend/src/container/NewWidget/index.tsx b/frontend/src/container/NewWidget/index.tsxindex 4943948abe..2ca25241a5 100644--- a/frontend/src/container/NewWidget/index.tsx+++ b/frontend/src/container/NewWidget/index.tsx@@ -1,14 +1,13 @@-import { Button } from 'antd';+import { Button, Modal, Typography } from 'antd';import ROUTES from 'constants/routes';import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';import history from 'lib/history';import { DashboardWidgetPageParams } from 'pages/DashboardWidget';import React, { useCallback, useEffect, useMemo, useState } from 'react';-import { connect, useSelector } from 'react-redux';+import { connect, useDispatch, useSelector } from 'react-redux';import { generatePath, useLocation, useParams } from 'react-router-dom';import { bindActionCreators, Dispatch } from 'redux';import { ThunkDispatch } from 'redux-thunk';-import { ApplySettingsToPanel, ApplySettingsToPanelProps } from 'store/actions';import {GetQueryResults,GetQueryResultsProps,@@ -17,17 +16,15 @@ import {SaveDashboard,SaveDashboardProps,} from 'store/actions/dashboard/saveDashboard';-import {- UpdateQuery,- UpdateQueryProps,-} from 'store/actions/dashboard/updateQuery';import { AppState } from 'store/reducers';import AppActions from 'types/actions';+import { FLUSH_DASHBOARD } from 'types/actions/dashboard';import { Widgets } from 'types/api/dashboard/getAll';import DashboardReducer from 'types/reducer/dashboards';import { GlobalReducer } from 'types/reducer/globalTime';import LeftContainer from './LeftContainer';+import QueryTypeTag from './LeftContainer/QueryTypeTag';import RightContainer from './RightContainer';import TimeItems, { timePreferance } from './RightContainer/timeItems';import {@@ -36,15 +33,15 @@ import {LeftContainerWrapper,PanelContainer,RightContainerWrapper,+ Tag,} from './styles';function NewWidget({selectedGraph,- applySettingsToPanel,saveSettingOfPanel,getQueryResults,- updateQuery,}: Props): JSX.Element {+ const dispatch = useDispatch();const { dashboards } = useSelector<AppState, DashboardReducer>((state) => state.dashboards,);@@ -87,6 +84,8 @@ function NewWidget({const [selectedNullZeroValue, setSelectedNullZeroValue] = useState<string>(selectedWidget?.nullZeroValues || 'zero',);+ const [saveModal, setSaveModal] = useState(false);+ const [hasUnstagedChanges, setHasUnstagedChanges] = useState(false);const getSelectedTime = useCallback(() =>@@ -116,45 +115,25 @@ function NewWidget({dashboardId,});}, [- opacity,+ saveSettingOfPanel,+ selectedDashboard.uuid,description,- query,- selectedTime,stacked,- title,selectedNullZeroValue,- saveSettingOfPanel,- selectedDashboard,- dashboardId,+ opacity,+ selectedTime.enum,+ title,yAxisUnit,+ query,+ dashboardId,]);- const onClickApplyHandler = (): void => {- selectedWidget?.query.forEach((element, index) => {- updateQuery({- widgetId: selectedWidget?.id || '',- query: element.query || '',- legend: element.legend || '',- currentIndex: index,- yAxisUnit,- });- });-- applySettingsToPanel({- description,- isStacked: stacked,- nullZeroValues: selectedNullZeroValue,- opacity,- timePreferance: selectedTime.enum,- title,- widgetId: selectedWidget?.id || '',- yAxisUnit,- });- };-const onClickDiscardHandler = useCallback(() => {+ dispatch({+ type: FLUSH_DASHBOARD,+ });history.push(generatePath(ROUTES.DASHBOARD, { dashboardId }));- }, [dashboardId]);+ }, [dashboardId, dispatch]);const getQueryResult = useCallback(() => {if (selectedWidget?.id.length !== 0) {@@ -182,14 +161,17 @@ function NewWidget({return (<Container><ButtonContainer>- <Button onClick={onClickSaveHandler}>Save</Button>- <Button onClick={onClickApplyHandler}>Apply</Button>+ <Button type="primary" onClick={(): void => setSaveModal(true)}>+ Save+ </Button>+ {/* <Button onClick={onClickApplyHandler}>Apply</Button> */}<Button onClick={onClickDiscardHandler}>Discard</Button></ButtonContainer><PanelContainer><LeftContainerWrapper flex={5}><LeftContainer+ handleUnstagedChanges={setHasUnstagedChanges}selectedTime={selectedTime}selectedGraph={selectedGraph}yAxisUnit={yAxisUnit}@@ -218,6 +200,34 @@ function NewWidget({/></RightContainerWrapper></PanelContainer>+ <Modal+ title="Save Changes"+ focusTriggerAfterClose+ forceRender+ destroyOnClose+ closable+ onCancel={(): void => setSaveModal(false)}+ onOk={(): void => {+ onClickSaveHandler();+ }}+ centered+ visible={saveModal}+ width={600}+ >+ {hasUnstagedChanges ? (+ <Typography>+ Looks like you have unstaged changes. Would you like to SAVE the last+ staged changes? If you want to stage new changes - Press{' '}+ <Tag>Stage & Run Query</Tag> and then try saving again.+ </Typography>+ ) : (+ <Typography>+ Your graph built with{' '}+ <QueryTypeTag queryType={selectedWidget?.query.queryType} /> query will be+ saved. Press OK to confirm.+ </Typography>+ )}+ </Modal></Container>);}@@ -228,27 +238,19 @@ export interface NewWidgetProps {}interface DispatchProps {- applySettingsToPanel: (- props: ApplySettingsToPanelProps,- ) => (dispatch: Dispatch<AppActions>) => void;saveSettingOfPanel: (props: SaveDashboardProps,) => (dispatch: Dispatch<AppActions>) => void;getQueryResults: (props: GetQueryResultsProps,) => (dispatch: Dispatch<AppActions>) => void;- updateQuery: (- props: UpdateQueryProps,- ) => (dispatch: Dispatch<AppActions>) => void;}const mapDispatchToProps = (dispatch: ThunkDispatch<unknown, unknown, AppActions>,): DispatchProps => ({- applySettingsToPanel: bindActionCreators(ApplySettingsToPanel, dispatch),saveSettingOfPanel: bindActionCreators(SaveDashboard, dispatch),getQueryResults: bindActionCreators(GetQueryResults, dispatch),- updateQuery: bindActionCreators(UpdateQuery, dispatch),});type Props = DispatchProps & NewWidgetProps;diff --git a/frontend/src/container/NewWidget/styles.ts b/frontend/src/container/NewWidget/styles.tsindex c5974baf45..386f044a0b 100644--- a/frontend/src/container/NewWidget/styles.ts+++ b/frontend/src/container/NewWidget/styles.ts@@ -1,4 +1,4 @@-import { Col } from 'antd';+import { Col, Tag as AntDTag } from 'antd';import styled from 'styled-components';export const Container = styled.div`@@ -31,3 +31,7 @@ export const ButtonContainer = styled.div`export const PanelContainer = styled.div`display: flex;`;++export const Tag = styled(AntDTag)`+ margin: 0;+`;diff --git a/frontend/src/lib/getChartData.ts b/frontend/src/lib/getChartData.tsindex 81b1c11d94..b1619fcd7a 100644--- a/frontend/src/lib/getChartData.ts+++ b/frontend/src/lib/getChartData.ts@@ -6,15 +6,15 @@ import convertIntoEpoc from './covertIntoEpoc';import { colors } from './getRandomColor';const getChartData = ({ queryData }: GetChartDataProps): ChartData => {- const response = queryData.map(({ query, queryData, legend }) => {+ const response = queryData.map(({ queryData }) => {return queryData.map((e) => {- const { values = [], metric } = e || {};+ const { values = [], metric, legend, queryName } = e || {};+const labelNames = getLabelName(metric,- query, // query- legend || '', // legends+ queryName || '', // query+ legend || '',);-const dataValue = values?.map((e) => {const [first = 0, second = ''] = e || [];return {@@ -30,7 +30,6 @@ const getChartData = ({ queryData }: GetChartDataProps): ChartData => {};});});-const allLabels = response.map((e) => e.map((e) => e.label)).reduce((a, b) => [...a, ...b], []);diff --git a/frontend/src/lib/getLabelName.ts b/frontend/src/lib/getLabelName.tsindex 0208e80920..44f0173450 100644--- a/frontend/src/lib/getLabelName.ts+++ b/frontend/src/lib/getLabelName.ts@@ -10,7 +10,6 @@ const getLabelName = (}const keysArray = Object.keys(metric);-if (legends.length !== 0) {const variables = legends.split('{{')@@ -30,7 +29,7 @@ const getLabelName = (const index = keysArray.findIndex((e) => e === '__name__');- const preArray = keysArray.slice(0, index);+ const preArray = index !== -1 ? keysArray.slice(0, index) : [];const postArray = keysArray.slice(index + 1, keysArray.length);if (index === undefined && preArray.length === 0 && postArray.length) {@@ -47,7 +46,6 @@ const getLabelName = (if (post.length === 0 && pre.length === 0) {return result;}-return `${result}{${pre}${post}}`;};diff --git a/frontend/src/lib/getMaxMinTime.ts b/frontend/src/lib/getMaxMinTime.tsindex b403da6e8a..483613c440 100644--- a/frontend/src/lib/getMaxMinTime.ts+++ b/frontend/src/lib/getMaxMinTime.ts@@ -19,7 +19,7 @@ const GetMaxMinTime = ({};interface GetMaxMinProps {- graphType: Widgets['panelTypes'];+ graphType: Widgets['panelTypes'] | null;maxTime: GlobalTime['maxTime'];minTime: GlobalTime['minTime'];}diff --git a/frontend/src/lib/query/GetFormulaName.ts b/frontend/src/lib/query/GetFormulaName.tsnew file mode 100644index 0000000000..b10b6203c0--- /dev/null+++ b/frontend/src/lib/query/GetFormulaName.ts@@ -0,0 +1,27 @@+import { sortBy } from 'lodash-es';++const MAX_QUERIES = 20;++function GetFormulaName(formulas = []): string | null {+ if (!formulas.length) return 'F1';+ if (formulas.length === MAX_QUERIES) {+ return null;+ }+ const formulasNameNumbered = sortBy(+ formulas.map(({ name }) => {+ return parseInt(name.slice(1), 10);+ }),+ (e) => e,+ );++ // let formulaIteratorIdx = 0;++ for (let charItr = 1; charItr <= MAX_QUERIES; charItr += 1) {+ if (!formulasNameNumbered.includes(charItr)) {+ return `F${charItr}`;+ }+ // formulaIteratorIdx += 1;+ }+}++export default GetFormulaName;diff --git a/frontend/src/lib/query/GetQueryName.ts b/frontend/src/lib/query/GetQueryName.tsnew file mode 100644index 0000000000..316b48d81a--- /dev/null+++ b/frontend/src/lib/query/GetQueryName.ts@@ -0,0 +1,29 @@+import { sortBy } from 'lodash-es';++const MAX_QUERIES = 26;+function GetQueryName(queries = []): string | null {+ if (!queries.length) return 'A';+ if (queries.length === MAX_QUERIES) {+ return null;+ }+ const sortedQueries = sortBy(queries, function (q) {+ return q.name;+ });++ let query_iterator_idx = 0;++ for (+ let charItr = 'A'.charCodeAt(0);+ charItr <= 'A'.charCodeAt(0) + MAX_QUERIES;+ charItr += 1+ ) {+ if (charItr !== sortedQueries[query_iterator_idx]?.name.charCodeAt(0)) {+ return String.fromCharCode(charItr);+ }+ query_iterator_idx += 1;+ }++ return null;+}++export default GetQueryName;diff --git a/frontend/src/store/actions/dashboard/getDashboard.ts b/frontend/src/store/actions/dashboard/getDashboard.tsindex 917365049e..4582a1255e 100644--- a/frontend/src/store/actions/dashboard/getDashboard.ts+++ b/frontend/src/store/actions/dashboard/getDashboard.ts@@ -1,8 +1,15 @@import getDashboard from 'api/dashboard/get';+import {+ ClickHouseQueryTemplate,+ PromQLQueryTemplate,+ QueryBuilderQueryTemplate,+} from 'constants/dashboard';import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';+import GetQueryName from 'lib/query/GetQueryName';import { Dispatch } from 'redux';import AppActions from 'types/actions';import { Props } from 'types/api/dashboard/get';+import { EQueryType } from 'types/common/dashboard';export const GetDashboard = ({uuid,@@ -37,18 +44,41 @@ export const GetDashboard = ({panelTypes: graphType || 'TIME_SERIES',timePreferance: 'GLOBAL_TIME',title: '',+ queryType: 0,queryData: {- data: [],+ data: [+ {+ queryData: [],+ },+ ],error: false,errorMessage: '',loading: false,},- query: [- {- query: '',- legend: '',+ query: {+ queryType: EQueryType.QUERY_BUILDER,+ promQL: [+ {+ name: GetQueryName([]) as string,+ ...PromQLQueryTemplate,+ },+ ],+ clickHouse: [+ {+ name: GetQueryName([]) as string,+ ...ClickHouseQueryTemplate,+ },+ ],+ metricsBuilder: {+ formulas: [],+ queryBuilder: [+ {+ name: GetQueryName([]) as string,+ ...QueryBuilderQueryTemplate,+ },+ ],},- ],+ },},});}diff --git a/frontend/src/store/actions/dashboard/getQueryResults.ts b/frontend/src/store/actions/dashboard/getQueryResults.tsindex e2ced192db..d2d8c6da6f 100644--- a/frontend/src/store/actions/dashboard/getQueryResults.ts+++ b/frontend/src/store/actions/dashboard/getQueryResults.ts@@ -1,91 +1,203 @@-import getQueryResult from 'api/widgets/getQuery';+import { getMetricsQueryRange } from 'api/metrics/getQueryRange';import { AxiosError } from 'axios';+import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';import { ITEMS } from 'container/NewDashboard/ComponentsSlider/menuItems';+import { WIDGET_QUERY_BUILDER_FORMULA_KEY_NAME } from 'container/NewWidget/LeftContainer/QuerySection/constants';+import { EQueryTypeToQueryKeyMapping } from 'container/NewWidget/LeftContainer/QuerySection/types';import { timePreferenceType } from 'container/NewWidget/RightContainer/timeItems';+import { Time } from 'container/TopNav/DateTimeSelection/config';import GetMaxMinTime from 'lib/getMaxMinTime';import GetMinMax from 'lib/getMinMax';import GetStartAndEndTime from 'lib/getStartAndEndTime';import getStep from 'lib/getStep';+import { isEmpty } from 'lodash-es';import { Dispatch } from 'redux';import store from 'store';import AppActions from 'types/actions';+import { ErrorResponse, SuccessResponse } from 'types/api';import { Query } from 'types/api/dashboard/getAll';+import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';+import { EDataSource, EPanelType, EQueryType } from 'types/common/dashboard';import { GlobalReducer } from 'types/reducer/globalTime';-export const GetQueryResults = (- props: GetQueryResultsProps,-): ((dispatch: Dispatch<AppActions>) => void) => {- return async (dispatch: Dispatch<AppActions>): Promise<void> => {- try {- const queryData = props.query;+export async function GetMetricQueryRange({+ query,+ globalSelectedInterval,+ graphType,+ selectedTime,+}: {+ query: Query;+ graphType: GRAPH_TYPES;+ selectedTime: timePreferenceType;+ globalSelectedInterval: Time;+}): Promise<SuccessResponse<MetricRangePayloadProps> | ErrorResponse> {+ const { queryType } = query;+ const queryKey: Record<EQueryTypeToQueryKeyMapping, string> =+ EQueryTypeToQueryKeyMapping[EQueryType[query.queryType]];+ const queryData = query[queryKey];+ const legendMap: Record<string, string> = {};+ const QueryPayload = {+ dataSource: EDataSource.METRICS,+ compositeMetricQuery: {+ queryType,+ panelType: EPanelType[graphType],+ },+ };+ switch (queryType as EQueryType) {+ case EQueryType.QUERY_BUILDER: {+ const builderQueries = {};+ queryData.queryBuilder.map((query) => {+ const generatedQueryPayload = {+ queryName: query.name,+ aggregateOperator: query.aggregateOperator,+ metricName: query.metricName,+ tagFilters: query.tagFilters,+ };- const { globalTime } = store.getState();+ if (graphType === 'TIME_SERIES') {+ generatedQueryPayload.groupBy = query.groupBy;+ }- const minMax = GetMinMax(props.globalSelectedInterval, [- globalTime.minTime / 1000000,- globalTime.maxTime / 1000000,- ]);+ // Value+ else {+ generatedQueryPayload.reduceTo = query.reduceTo;+ }- const getMaxMinTime = GetMaxMinTime({- graphType: props.graphType,- maxTime: minMax.maxTime,- minTime: minMax.minTime,+ generatedQueryPayload.expression = query.name;+ generatedQueryPayload.disabled = query.disabled;+ builderQueries[query.name] = generatedQueryPayload;+ legendMap[query.name] = query.legend || '';});- const { end, start } = GetStartAndEndTime({- type: props.selectedTime,- maxTime: getMaxMinTime.maxTime,- minTime: getMaxMinTime.minTime,+ queryData[WIDGET_QUERY_BUILDER_FORMULA_KEY_NAME].map((formula) => {+ const generatedFormulaPayload = {};+ generatedFormulaPayload.queryName = formula.name;+ generatedFormulaPayload.expression = formula.expression;+ generatedFormulaPayload.disabled = formula.disabled;+ builderQueries[formula.name] = generatedFormulaPayload;+ });+ QueryPayload.compositeMetricQuery.builderQueries = builderQueries;+ break;+ }+ case EQueryType.CLICKHOUSE: {+ const chQueries = {};+ queryData.map((query) => {+ if (!query.rawQuery) return;+ chQueries[query.name] = {+ query: query.rawQuery,+ disabled: query.disabled,+ };+ legendMap[query.name] = query.legend;+ });+ QueryPayload.compositeMetricQuery.chQueries = chQueries;+ break;+ }+ case EQueryType.PROM: {+ const promQueries = {};+ queryData.map((query) => {+ if (!query.query) return;+ promQueries[query.name] = {+ query: query.query,+ disabled: query.disabled,+ };+ legendMap[query.name] = query.legend;});+ QueryPayload.compositeMetricQuery.promQueries = promQueries;+ break;+ }+ default:+ return;+ }++ const { globalTime } = store.getState();++ const minMax = GetMinMax(globalSelectedInterval, [+ globalTime.minTime / 1000000,+ globalTime.maxTime / 1000000,+ ]);++ const getMaxMinTime = GetMaxMinTime({+ graphType: null,+ maxTime: minMax.maxTime,+ minTime: minMax.minTime,+ });++ const { end, start } = GetStartAndEndTime({+ type: selectedTime,+ maxTime: getMaxMinTime.maxTime,+ minTime: getMaxMinTime.minTime,+ });+ const response = await getMetricsQueryRange({+ start: parseInt(start, 10) * 1e3,+ end: parseInt(end, 10) * 1e3,+ step: getStep({ start, end, inputFormat: 'ms' }),+ ...QueryPayload,+ });+ if (response.statusCode >= 400) {+ throw new Error(+ `API responded with ${response.statusCode} - ${response.error}`,+ );+ }- const response = await Promise.all(- queryData- .filter((e) => e.query)- .map(async (query) => {- const result = await getQueryResult({- end,- query: encodeURIComponent(query.query),- start,- step: `${getStep({ start, end, inputFormat: 'ms' })}`,- });- return {- query: query.query,- queryData: result,- legend: query.legend,- };- }),- );-- const isError = response.find(- ({ queryData }) => queryData.statusCode !== 200,- );-- // want to make sure query is not empty- const isEmptyQuery =- queryData.map((e) => e.query).filter((e) => e).length ===- queryData.map((e) => e.query).length;-- if (isError !== undefined && isEmptyQuery) {+ if (response.payload?.data?.result) {+ response.payload.data.result = response.payload.data.result.map(+ (queryData) => {+ const newQueryData = queryData;+ newQueryData.legend = legendMap[queryData.queryName];+ if (isEmpty(queryData.metric)) {+ newQueryData.metric[queryData.queryName] = queryData.queryName;+ newQueryData.legend = queryData.queryName;+ }+ return queryData;+ },+ );+ }+ return response;+}++export const GetQueryResults = (+ props: GetQueryResultsProps,+): ((dispatch: Dispatch<AppActions>) => void) => {+ return async (dispatch: Dispatch<AppActions>): Promise<void> => {+ try {+ const response = await GetMetricQueryRange(props);++ const isError = response.error;++ if (isError != null) {dispatch({type: 'QUERY_ERROR',payload: {- errorMessage: isError.queryData.error || '',+ errorMessage: isError || '',widgetId: props.widgetId,},});+ return;}- const data = response.map((e) => ({- query: e.query,- legend: e.legend || '',- queryData: e.queryData.payload?.result || [],- }));+ // const data = response.map((e) => ({+ // query: e.query,+ // legend: e.legend || '',+ // queryData: e.queryData.payload?.result || [],+ // }));dispatch({type: 'QUERY_SUCCESS',payload: {widgetId: props.widgetId,- data,+ data: {+ queryData: response.payload?.data?.result+ ? response.payload?.data?.result+ : [],+ },+ },+ });+ dispatch({+ type: 'QUERY_ERROR',+ payload: {+ errorMessage: '',+ widgetId: props.widgetId,+ errorBoolean: false,},});} catch (error) {@@ -94,6 +206,7 @@ export const GetQueryResults = (payload: {errorMessage: (error as AxiosError).toString(),widgetId: props.widgetId,+ errorBoolean: true,},});}diff --git a/frontend/src/store/actions/dashboard/saveDashboard.ts b/frontend/src/store/actions/dashboard/saveDashboard.tsindex a1e28d3efe..101a7e30e0 100644--- a/frontend/src/store/actions/dashboard/saveDashboard.ts+++ b/frontend/src/store/actions/dashboard/saveDashboard.ts@@ -84,7 +84,6 @@ export const SaveDashboard = ({};const allLayout = getAllLayout();-const response = await updateDashboardApi({data: {...selectedDashboard.data,diff --git a/frontend/src/store/actions/dashboard/updateQuery.ts b/frontend/src/store/actions/dashboard/updateQuery.tsindex 49ff7c7439..0e00c21948 100644--- a/frontend/src/store/actions/dashboard/updateQuery.ts+++ b/frontend/src/store/actions/dashboard/updateQuery.ts@@ -1,5 +1,4 @@import { Dispatch } from 'redux';-import store from 'store';import AppActions from 'types/actions';import { Query } from 'types/api/dashboard/getAll';@@ -7,29 +6,10 @@ export const UpdateQuery = (props: UpdateQueryProps,): ((dispatch: Dispatch<AppActions>) => void) => {return (dispatch: Dispatch<AppActions>): void => {- const state = store.getState();- const { dashboards } = state.dashboards;- const [selectedDashboard] = dashboards;- const { data } = selectedDashboard;- const { widgets = [] } = data;- const selectedWidgetIndex = widgets.findIndex((e) => e.id === props.widgetId);- const selectedWidget = widgets[selectedWidgetIndex];- const { query } = selectedWidget;- const preQuery = query.slice(0, props.currentIndex);- const afterQuery = query.slice(props.currentIndex + 1, query.length);- const queryArray: Query[] = [- ...preQuery,- {- query: props.query,- legend: props.legend,- },- ...afterQuery,- ];-dispatch({type: 'UPDATE_QUERY',payload: {- query: queryArray,+ query: props.updatedQuery,widgetId: props.widgetId,yAxisUnit: props.yAxisUnit,},@@ -38,9 +18,10 @@ export const UpdateQuery = (};export interface UpdateQueryProps {+ // query: string;+ // legend: string;+ // currentIndex: number;+ updatedQuery: Query;widgetId: string;- query: string;- legend: string;- currentIndex: number;yAxisUnit: string | undefined;}diff --git a/frontend/src/store/actions/dashboard/updateQueryType.ts b/frontend/src/store/actions/dashboard/updateQueryType.tsnew file mode 100644index 0000000000..f8f4ee1b29--- /dev/null+++ b/frontend/src/store/actions/dashboard/updateQueryType.ts@@ -0,0 +1,21 @@+import { Dispatch } from 'redux';+import AppActions from 'types/actions';++export const UpdateQueryType = (+ props: UpdateQueryTypeProps,+): ((dispatch: Dispatch<AppActions>) => void) => {+ return (dispatch: Dispatch<AppActions>): void => {+ dispatch({+ type: 'UPDATE_QUERY_TYPE',+ payload: {+ queryType: props.queryType,+ widgetId: props.widgetId,+ },+ });+ };+};++export interface UpdateQueryTypeProps {+ widgetId: string;+ queryType: number;+}diff --git a/frontend/src/store/reducers/dashboard.ts b/frontend/src/store/reducers/dashboard.tsindex d205341e44..4d7656993e 100644--- a/frontend/src/store/reducers/dashboard.ts+++ b/frontend/src/store/reducers/dashboard.ts@@ -1,11 +1,11 @@import {APPLY_SETTINGS_TO_PANEL,CREATE_DEFAULT_WIDGET,- CREATE_NEW_QUERY,DashboardActions,DELETE_DASHBOARD_SUCCESS,- DELETE_QUERY,+ // DELETE_QUERY,DELETE_WIDGET_SUCCESS,+ FLUSH_DASHBOARD,GET_ALL_DASHBOARD_ERROR,GET_ALL_DASHBOARD_LOADING_START,GET_ALL_DASHBOARD_SUCCESS,@@ -19,6 +19,7 @@ import {TOGGLE_EDIT_MODE,UPDATE_DASHBOARD,UPDATE_QUERY,+ UPDATE_QUERY_TYPE,UPDATE_TITLE_DESCRIPTION_TAGS_SUCCESS,} from 'types/actions/dashboard';import InitialValueTypes from 'types/reducer/dashboards';@@ -134,7 +135,6 @@ const dashboard = (// NOTE: this action will will be dispatched in the single dashboard onlycase CREATE_DEFAULT_WIDGET: {const [selectedDashboard] = state.dashboards;-const { data } = selectedDashboard;const { widgets } = data;const defaultWidget = action.payload;@@ -169,56 +169,8 @@ const dashboard = (};}- case CREATE_NEW_QUERY: {- const [selectedDashboard] = state.dashboards;-- const { data } = selectedDashboard;- const { widgets } = data;- const selectedWidgetId = action.payload.widgetId;- const selectedWidgetIndex = data.widgets?.findIndex(- (e) => e.id === selectedWidgetId,- );-- const preWidget = data.widgets?.slice(0, selectedWidgetIndex);- const afterWidget = data.widgets?.slice(- (selectedWidgetIndex || 0) + 1, // this is never undefined- widgets?.length,- );-- const selectedWidget = (data.widgets || [])[selectedWidgetIndex || 0];-- // this condition will never run as there will a widget with this widgetId- if (selectedWidget === undefined) {- return {- ...state,- };- }-- const newQuery = [...selectedWidget.query, { query: '', legend: '' }];-- return {- ...state,- dashboards: [- {- ...selectedDashboard,- data: {- ...data,- widgets: [- ...(preWidget || []),- {- ...selectedWidget,- query: newQuery,- },- ...(afterWidget || []),- ],- },- },- ],- };- }-case QUERY_ERROR: {- const { widgetId, errorMessage } = action.payload;+ const { widgetId, errorMessage, errorBoolean = true } = action.payload;const [selectedDashboard] = state.dashboards;const { data } = selectedDashboard;@@ -249,7 +201,7 @@ const dashboard = (...selectedWidget,queryData: {...selectedWidget.queryData,- error: true,+ error: errorBoolean,errorMessage,},},@@ -291,7 +243,7 @@ const dashboard = ({...selectedWidget,queryData: {- data: [...queryDataResponse],+ data: [queryDataResponse],error: selectedWidget.queryData.error,errorMessage: selectedWidget.queryData.errorMessage,loading: false,@@ -370,6 +322,12 @@ const dashboard = (};}+ case FLUSH_DASHBOARD: {+ return {+ ...state,+ dashboards: [],+ };+ }case DELETE_WIDGET_SUCCESS: {const { widgetId, layout } = action.payload;@@ -439,9 +397,8 @@ const dashboard = (],};}-- case DELETE_QUERY: {- const { currentIndex, widgetId } = action.payload;+ case UPDATE_QUERY_TYPE: {+ const { widgetId, queryType } = action.payload;const { dashboards } = state;const [selectedDashboard] = dashboards;const { data } = selectedDashboard;@@ -458,11 +415,6 @@ const dashboard = (const selectedWidget = widgets[selectedWidgetIndex];- const { query } = selectedWidget;-- const preQuery = query.slice(0, currentIndex);- const postQuery = query.slice(currentIndex + 1, query.length);-return {...state,dashboards: [@@ -474,7 +426,7 @@ const dashboard = (...preWidget,{...selectedWidget,- query: [...preQuery, ...postQuery],+ queryType,},...afterWidget,],@@ -484,6 +436,50 @@ const dashboard = (};}+ // case DELETE_QUERY: {+ // const { currentIndex, widgetId } = action.payload;+ // const { dashboards } = state;+ // const [selectedDashboard] = dashboards;+ // const { data } = selectedDashboard;+ // const { widgets = [] } = data;++ // const selectedWidgetIndex = widgets.findIndex((e) => e.id === widgetId) || 0;++ // const preWidget = widgets?.slice(0, selectedWidgetIndex) || [];+ // const afterWidget =+ // widgets?.slice(+ // selectedWidgetIndex + 1, // this is never undefined+ // widgets.length,+ // ) || [];++ // const selectedWidget = widgets[selectedWidgetIndex];++ // const { query } = selectedWidget;++ // const preQuery = query.slice(0, currentIndex);+ // const postQuery = query.slice(currentIndex + 1, query.length);++ // return {+ // ...state,+ // dashboards: [+ // {+ // ...selectedDashboard,+ // data: {+ // ...data,+ // widgets: [+ // ...preWidget,+ // {+ // ...selectedWidget,+ // query: [...preQuery, ...postQuery],+ // },+ // ...afterWidget,+ // ],+ // },+ // },+ // ],+ // };+ // }+default:return state;}diff --git a/frontend/src/types/actions/dashboard.ts b/frontend/src/types/actions/dashboard.tsindex 5f60ce747d..c1051d542f 100644--- a/frontend/src/types/actions/dashboard.ts+++ b/frontend/src/types/actions/dashboard.ts@@ -25,7 +25,6 @@ export const DELETE_DASHBOARD_ERROR = 'DELETE_DASHBOARD_ERROR';export const CREATE_DEFAULT_WIDGET = 'CREATE_DEFAULT_WIDGET';-export const CREATE_NEW_QUERY = 'CREATE_NEW_QUERY';export const QUERY_SUCCESS = 'QUERY_SUCCESS';export const QUERY_ERROR = 'QUERY_ERROR';@@ -42,7 +41,8 @@ export const DELETE_WIDGET_ERROR = 'DELETE_WIDGET_ERROR';export const IS_ADD_WIDGET = 'IS_ADD_WIDGET';export const DELETE_QUERY = 'DELETE_QUERY';-+export const UPDATE_QUERY_TYPE = 'UPDATE_QUERY_TYPE';+export const FLUSH_DASHBOARD = 'FLUSH_DASHBOARD';interface GetDashboard {type: typeof GET_DASHBOARD;payload: Dashboard;@@ -85,13 +85,6 @@ interface CreateDefaultWidget {payload: Widgets;}-interface CreateNewQuery {- type: typeof CREATE_NEW_QUERY;- payload: {- widgetId: string;- };-}-interface IsAddWidget {type: typeof IS_ADD_WIDGET;payload: {@@ -127,7 +120,11 @@ interface ToggleEditMode {export interface QuerySuccessPayload {widgetId: string;- data: { legend: string; queryData: QueryData[]; query: string }[];+ data: {+ // legend: string;+ queryData: QueryData[];+ // query: string+ }[];}interface QuerySuccess {type: typeof QUERY_SUCCESS;@@ -137,7 +134,7 @@ interface QuerySuccess {interface UpdateQuery {type: typeof UPDATE_QUERY;payload: {- query: Query[];+ query: Query;widgetId: string;yAxisUnit: string | undefined;};@@ -148,6 +145,7 @@ interface QueryError {payload: {errorMessage: string;widgetId: string;+ errorBoolean?: boolean;};}@@ -174,6 +172,18 @@ interface DeleteQuery {payload: DeleteQueryProps;}+interface UpdateQueryType {+ type: typeof UPDATE_QUERY_TYPE;+ payload: {+ queryType: number;+ widgetId: string;+ };+}++interface FlushDashboard {+ type: typeof FLUSH_DASHBOARD;+}+export type DashboardActions =| GetDashboard| UpdateDashboard@@ -185,7 +195,6 @@ export type DashboardActions =| UpdateDashboardTitle| ToggleEditMode| CreateDefaultWidget- | CreateNewQuery| QuerySuccess| QueryError| ApplySettingsToPanel@@ -193,4 +202,6 @@ export type DashboardActions =| WidgetDeleteSuccess| IsAddWidget| UpdateQuery- | DeleteQuery;+ | DeleteQuery+ | UpdateQueryType+ | FlushDashboard;diff --git a/frontend/src/types/api/dashboard/getAll.ts b/frontend/src/types/api/dashboard/getAll.tsindex fa01e809fb..66710016da 100644--- a/frontend/src/types/api/dashboard/getAll.ts+++ b/frontend/src/types/api/dashboard/getAll.ts@@ -1,6 +1,7 @@import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';import { timePreferenceType } from 'container/NewWidget/RightContainer/timeItems';import { Layout } from 'react-grid-layout';+import { EAggregateOperator, EQueryType } from 'types/common/dashboard';import { QueryData } from '../widgets/getQuery';@@ -23,7 +24,7 @@ export interface DashboardData {layout?: Layout[];}-export interface Widgets {+export interface IBaseWidget {isStacked: boolean;id: string;panelTypes: GRAPH_TYPES;@@ -32,22 +33,72 @@ export interface Widgets {opacity: string;nullZeroValues: string;timePreferance: timePreferenceType;- query: Query[];queryData: {loading: boolean;error: boolean;errorMessage: string;data: {- legend?: string;+ // legend?: string;queryData: QueryData[];- query: string;+ // query: string;}[];};stepSize?: number;yAxisUnit?: string;}+export interface Widgets extends IBaseWidget {+ query: Query;+}+export interface PromQLWidgets extends IBaseWidget {+ query: { query: string; legend: string }[];+}export interface Query {+ queryType: EQueryType;+ promQL: IPromQLQuery[];+ metricsBuilder: {+ formulas: IMetricsBuilderFormula[];+ queryBuilder: IMetricsBuilderQuery[];+ };+ clickHouse: IClickHouseQuery[];+}++export interface IMetricsBuilderFormula {+ expression: string;+ disabled: boolean;+ name: string;+}+export interface IMetricsBuilderQuery {+ aggregateOperator: EAggregateOperator;+ disabled: boolean;+ name: string;+ legend: string;+ metricName: string | null;+ groupBy: string[];+ tagFilters: IQueryBuilderTagFilters;+}++export interface IQueryBuilderTagFilters {+ op: string;+ items:+ | {+ id: string;+ key: string;+ op: string;+ value: string[];+ }[]+ | [];+}++export interface IClickHouseQuery {+ name: string;+ rawQuery: string;+ legend: string;+ disabled: boolean;+}+export interface IPromQLQuery {query: string;- legend?: string;+ legend: string;+ disabled: boolean;+ name: string;}diff --git a/frontend/src/types/api/dashboard/shared.ts b/frontend/src/types/api/dashboard/shared.tsnew file mode 100644index 0000000000..31778e79bc--- /dev/null+++ b/frontend/src/types/api/dashboard/shared.ts@@ -0,0 +1,5 @@+export enum EQueryTypeToQueryKeyMapping {+ QUERY_BUILDER = 'metricsBuilder',+ CLICKHOUSE = 'clickHouse',+ PROM = 'promQL',+}diff --git a/frontend/src/types/api/metrics/getMetricName.ts b/frontend/src/types/api/metrics/getMetricName.tsnew file mode 100644index 0000000000..881653085c--- /dev/null+++ b/frontend/src/types/api/metrics/getMetricName.ts@@ -0,0 +1,4 @@+export type MetricNameProps = string;+export type MetricNamesPayloadProps = {+ data: string[];+};diff --git a/frontend/src/types/api/metrics/getQueryRange.ts b/frontend/src/types/api/metrics/getQueryRange.tsnew file mode 100644index 0000000000..742a0608f0--- /dev/null+++ b/frontend/src/types/api/metrics/getQueryRange.ts@@ -0,0 +1,9 @@+import { QueryData } from '../widgets/getQuery';++export type MetricsRangeProps = any;+export interface MetricRangePayloadProps {+ data: {+ result: QueryData[];+ resultType: string;+ };+}diff --git a/frontend/src/types/api/metrics/getResourceAttributes.ts b/frontend/src/types/api/metrics/getResourceAttributes.tsindex 04b35255c9..8183cfbe2a 100644--- a/frontend/src/types/api/metrics/getResourceAttributes.ts+++ b/frontend/src/types/api/metrics/getResourceAttributes.ts@@ -1,8 +1,15 @@+export type TagKeyProps = {+ match?: string;+ metricName: string;+};export type TagKeysPayloadProps = {data: string[];};-export type TagValueProps = string;+export type TagValueProps = {+ tagKey: string;+ metricName: string;+};export type TagValuesPayloadProps = {data: string[];};diff --git a/frontend/src/types/api/widgets/getQuery.ts b/frontend/src/types/api/widgets/getQuery.tsindex e6c3a3d504..6e97d116e8 100644--- a/frontend/src/types/api/widgets/getQuery.ts+++ b/frontend/src/types/api/widgets/getQuery.ts@@ -8,6 +8,7 @@ export interface QueryData {__name__: string;[key: string]: string;};+ queryName: string;values: [number, string][];}diff --git a/frontend/src/types/common/dashboard.ts b/frontend/src/types/common/dashboard.tsnew file mode 100644index 0000000000..c8ae2bd9d9--- /dev/null+++ b/frontend/src/types/common/dashboard.ts@@ -0,0 +1,50 @@+export enum EDataSource {+ METRICS = 1,+ TRACES,+ LOGS,+}++export enum EQueryType {+ QUERY_BUILDER = 1,+ CLICKHOUSE,+ PROM,+}++export enum EAggregateOperator {+ NOOP = 1,+ COUNT = 2,+ COUNT_DISTINCT = 3,+ SUM = 4,+ AVG = 5,+ MAX = 6,+ MIN = 7,+ P05 = 8,+ P10 = 9,+ P20 = 10,+ P25 = 11,+ P50 = 12,+ P75 = 13,+ P90 = 14,+ P95 = 15,+ P99 = 16,+ RATE = 17,+ SUM_RATE = 18,+ // leaving gap for possible future {X}_RATE+ RATE_SUM = 22,+ RATE_AVG = 23,+ RATE_MAX = 24,+ RATE_MIN = 25,+}++export enum EPanelType {+ TIME_SERIES = 1,+ VALUE,+}++export enum EReduceOperator {+ 'Latest of values in timeframe' = 1, // LAST+ 'Sum of values in timeframe', // SUM+ 'Average of values in timeframe', // AVG+ 'Max of values in timeframe', // MAX+ 'Min of values in timeframe', // MIN+}