Compare commits

..

18 Commits

Author SHA1 Message Date
SagarRajput-7
7f0809b81a Merge branch 'main' into base-path-config 2026-04-16 16:24:46 +05:30
SagarRajput-7
17e6d27698 feat: removed plugin and serving the index.html only as the template 2026-04-15 20:52:04 +05:30
SagarRajput-7
09dfadb1ea feat: refactor the interceptor and added gotmpl into gitignore 2026-04-15 20:14:54 +05:30
SagarRajput-7
04e01474ff feat: changed output path to dir level 2026-04-15 19:53:57 +05:30
SagarRajput-7
6c07b60f06 feat: base path config setup and plugin for gotmpl generation at build time 2026-04-15 18:56:48 +05:30
SagarRajput-7
7208777ca6 chore: public dir cleanup, remove duplicate assets since they are moved to src/assets 2026-04-15 17:43:10 +05:30
SagarRajput-7
ad3e0527ce chore: addressed comments 2026-04-15 03:04:55 +05:30
SagarRajput-7
555dc5881e Merge branch 'main' into asset-consumption 2026-04-15 02:38:27 +05:30
SagarRajput-7
4761fcb57a chore: addressed comments and added public reference rule 2026-04-15 02:37:34 +05:30
SagarRajput-7
bda93ee286 Merge branch 'main' into asset-consumption 2026-04-14 16:55:41 +05:30
SagarRajput-7
7edc737076 chore: addressed feedback comments 2026-04-14 16:54:56 +05:30
SagarRajput-7
4fa306f94f chore: strengthen the lint rule and migration the gaps found 2026-04-14 16:11:21 +05:30
SagarRajput-7
c415b2a1d7 chore: fmt fix 2026-04-14 15:16:46 +05:30
SagarRajput-7
d513188511 chore: code refactor 2026-04-14 15:16:46 +05:30
SagarRajput-7
e7edc5da82 chore: asset migration - using the src/assets across the codebase, instead of the public dir 2026-04-14 15:16:46 +05:30
SagarRajput-7
dae7a43a52 chore: added eslint and stylelint for the asset migration task 2026-04-14 15:16:46 +05:30
SagarRajput-7
9fb373e36b chore: remove the snapshot update since no migration is done under this pr 2026-04-14 15:16:46 +05:30
SagarRajput-7
b01d4d8a74 chore: jest module resolution fix 2026-04-14 15:16:46 +05:30
46 changed files with 564 additions and 729 deletions

View File

@@ -7,12 +7,12 @@ This guide explains how to add new data sources to the SigNoz onboarding flow. T
The configuration is located at:
```
frontend/src/container/OnboardingV2Container/onboarding-configs/onboarding-config-with-links.ts
frontend/src/container/OnboardingV2Container/onboarding-configs/onboarding-config-with-links.json
```
## Structure Overview
## JSON Structure Overview
The configuration file exports a TypeScript array (`onboardingConfigWithLinks`) containing data source objects. Each object represents a selectable option in the onboarding flow. SVG logos are imported as ES modules at the top of the file.
The configuration file is a JSON array containing data source objects. Each object represents a selectable option in the onboarding flow.
## Data Source Object Keys
@@ -24,7 +24,7 @@ The configuration file exports a TypeScript array (`onboardingConfigWithLinks`)
| `label` | `string` | Display name shown to users (e.g., `"AWS EC2"`) |
| `tags` | `string[]` | Array of category tags for grouping (e.g., `["AWS"]`, `["database"]`) |
| `module` | `string` | Destination module after onboarding completion |
| `imgUrl` | `string` | Imported SVG URL **(SVG required)** (e.g., `import ec2Url from '@/assets/Logos/ec2.svg'`, then use `ec2Url`) |
| `imgUrl` | `string` | Path to the logo/icon **(SVG required)** (e.g., `"/Logos/ec2.svg"`) |
### Optional Keys
@@ -57,34 +57,36 @@ The `module` key determines where users are redirected after completing onboardi
The `question` object enables multi-step selection flows:
```ts
question: {
desc: 'What would you like to monitor?',
type: 'select',
helpText: 'Choose the telemetry type you want to collect.',
helpLink: '/docs/azure-monitoring/overview/',
helpLinkText: 'Read the guide →',
options: [
{
key: 'logging',
label: 'Logs',
imgUrl: azureVmUrl,
link: '/docs/azure-monitoring/app-service/logging/',
},
{
key: 'metrics',
label: 'Metrics',
imgUrl: azureVmUrl,
link: '/docs/azure-monitoring/app-service/metrics/',
},
{
key: 'tracing',
label: 'Traces',
imgUrl: azureVmUrl,
link: '/docs/azure-monitoring/app-service/tracing/',
},
],
},
```json
{
"question": {
"desc": "What would you like to monitor?",
"type": "select",
"helpText": "Choose the telemetry type you want to collect.",
"helpLink": "/docs/azure-monitoring/overview/",
"helpLinkText": "Read the guide →",
"options": [
{
"key": "logging",
"label": "Logs",
"imgUrl": "/Logos/azure-vm.svg",
"link": "/docs/azure-monitoring/app-service/logging/"
},
{
"key": "metrics",
"label": "Metrics",
"imgUrl": "/Logos/azure-vm.svg",
"link": "/docs/azure-monitoring/app-service/metrics/"
},
{
"key": "tracing",
"label": "Traces",
"imgUrl": "/Logos/azure-vm.svg",
"link": "/docs/azure-monitoring/app-service/tracing/"
}
]
}
}
```
### Question Keys
@@ -104,161 +106,152 @@ Options can be simple (direct link) or nested (with another question):
### Simple Option (Direct Link)
```ts
```json
{
key: 'aws-ec2-logs',
label: 'Logs',
imgUrl: ec2Url,
link: '/docs/userguide/collect_logs_from_file/',
},
"key": "aws-ec2-logs",
"label": "Logs",
"imgUrl": "/Logos/ec2.svg",
"link": "/docs/userguide/collect_logs_from_file/"
}
```
### Option with Internal Redirect
```ts
```json
{
key: 'aws-ec2-metrics-one-click',
label: 'One Click AWS',
imgUrl: ec2Url,
link: '/integrations?integration=aws-integration&service=ec2',
internalRedirect: true,
},
"key": "aws-ec2-metrics-one-click",
"label": "One Click AWS",
"imgUrl": "/Logos/ec2.svg",
"link": "/integrations?integration=aws-integration&service=ec2",
"internalRedirect": true
}
```
> **Important**: Set `internalRedirect: true` only for internal app routes (like `/integrations?...`). Docs links should NOT have this flag.
### Nested Option (Multi-step Flow)
```ts
```json
{
key: 'aws-ec2-metrics',
label: 'Metrics',
imgUrl: ec2Url,
question: {
desc: 'How would you like to set up monitoring?',
helpText: 'Choose your setup method.',
options: [...],
},
},
"key": "aws-ec2-metrics",
"label": "Metrics",
"imgUrl": "/Logos/ec2.svg",
"question": {
"desc": "How would you like to set up monitoring?",
"helpText": "Choose your setup method.",
"options": [...]
}
}
```
## Examples
### Simple Data Source (Direct Link)
```ts
import elbUrl from '@/assets/Logos/elb.svg';
// inside the onboardingConfigWithLinks array:
```json
{
dataSource: 'aws-elb',
label: 'AWS ELB',
tags: ['AWS'],
module: 'logs',
relatedSearchKeywords: [
'aws',
'aws elb',
'elb logs',
'elastic load balancer',
"dataSource": "aws-elb",
"label": "AWS ELB",
"tags": ["AWS"],
"module": "logs",
"relatedSearchKeywords": [
"aws",
"aws elb",
"elb logs",
"elastic load balancer"
],
imgUrl: elbUrl,
link: '/docs/aws-monitoring/elb/',
},
"imgUrl": "/Logos/elb.svg",
"link": "/docs/aws-monitoring/elb/"
}
```
### Data Source with Single Question Level
```ts
import azureVmUrl from '@/assets/Logos/azure-vm.svg';
// inside the onboardingConfigWithLinks array:
```json
{
dataSource: 'app-service',
label: 'App Service',
imgUrl: azureVmUrl,
tags: ['Azure'],
module: 'apm',
relatedSearchKeywords: ['azure', 'app service'],
question: {
desc: 'What telemetry data do you want to visualise?',
type: 'select',
options: [
"dataSource": "app-service",
"label": "App Service",
"imgUrl": "/Logos/azure-vm.svg",
"tags": ["Azure"],
"module": "apm",
"relatedSearchKeywords": ["azure", "app service"],
"question": {
"desc": "What telemetry data do you want to visualise?",
"type": "select",
"options": [
{
key: 'logging',
label: 'Logs',
imgUrl: azureVmUrl,
link: '/docs/azure-monitoring/app-service/logging/',
"key": "logging",
"label": "Logs",
"imgUrl": "/Logos/azure-vm.svg",
"link": "/docs/azure-monitoring/app-service/logging/"
},
{
key: 'metrics',
label: 'Metrics',
imgUrl: azureVmUrl,
link: '/docs/azure-monitoring/app-service/metrics/',
"key": "metrics",
"label": "Metrics",
"imgUrl": "/Logos/azure-vm.svg",
"link": "/docs/azure-monitoring/app-service/metrics/"
},
{
key: 'tracing',
label: 'Traces',
imgUrl: azureVmUrl,
link: '/docs/azure-monitoring/app-service/tracing/',
},
],
},
},
"key": "tracing",
"label": "Traces",
"imgUrl": "/Logos/azure-vm.svg",
"link": "/docs/azure-monitoring/app-service/tracing/"
}
]
}
}
```
### Data Source with Nested Questions (2-3 Levels)
```ts
import ec2Url from '@/assets/Logos/ec2.svg';
// inside the onboardingConfigWithLinks array:
```json
{
dataSource: 'aws-ec2',
label: 'AWS EC2',
tags: ['AWS'],
module: 'logs',
relatedSearchKeywords: ['aws', 'aws ec2', 'ec2 logs', 'ec2 metrics'],
imgUrl: ec2Url,
question: {
desc: 'What would you like to monitor for AWS EC2?',
type: 'select',
helpText: 'Choose the type of telemetry data you want to collect.',
options: [
"dataSource": "aws-ec2",
"label": "AWS EC2",
"tags": ["AWS"],
"module": "logs",
"relatedSearchKeywords": ["aws", "aws ec2", "ec2 logs", "ec2 metrics"],
"imgUrl": "/Logos/ec2.svg",
"question": {
"desc": "What would you like to monitor for AWS EC2?",
"type": "select",
"helpText": "Choose the type of telemetry data you want to collect.",
"options": [
{
key: 'aws-ec2-logs',
label: 'Logs',
imgUrl: ec2Url,
link: '/docs/userguide/collect_logs_from_file/',
"key": "aws-ec2-logs",
"label": "Logs",
"imgUrl": "/Logos/ec2.svg",
"link": "/docs/userguide/collect_logs_from_file/"
},
{
key: 'aws-ec2-metrics',
label: 'Metrics',
imgUrl: ec2Url,
question: {
desc: 'How would you like to set up EC2 Metrics monitoring?',
helpText: 'One Click uses AWS CloudWatch integration. Manual setup uses OpenTelemetry.',
helpLink: '/docs/aws-monitoring/one-click-vs-manual/',
helpLinkText: 'Read the comparison guide →',
options: [
"key": "aws-ec2-metrics",
"label": "Metrics",
"imgUrl": "/Logos/ec2.svg",
"question": {
"desc": "How would you like to set up EC2 Metrics monitoring?",
"helpText": "One Click uses AWS CloudWatch integration. Manual setup uses OpenTelemetry.",
"helpLink": "/docs/aws-monitoring/one-click-vs-manual/",
"helpLinkText": "Read the comparison guide →",
"options": [
{
key: 'aws-ec2-metrics-one-click',
label: 'One Click AWS',
imgUrl: ec2Url,
link: '/integrations?integration=aws-integration&service=ec2',
internalRedirect: true,
"key": "aws-ec2-metrics-one-click",
"label": "One Click AWS",
"imgUrl": "/Logos/ec2.svg",
"link": "/integrations?integration=aws-integration&service=ec2",
"internalRedirect": true
},
{
key: 'aws-ec2-metrics-manual',
label: 'Manual Setup',
imgUrl: ec2Url,
link: '/docs/tutorial/opentelemetry-binary-usage-in-virtual-machine/',
},
],
},
},
],
},
},
"key": "aws-ec2-metrics-manual",
"label": "Manual Setup",
"imgUrl": "/Logos/ec2.svg",
"link": "/docs/tutorial/opentelemetry-binary-usage-in-virtual-machine/"
}
]
}
}
]
}
}
```
## Best Practices
@@ -277,16 +270,11 @@ import ec2Url from '@/assets/Logos/ec2.svg';
### 3. Logos
- Place logo files in `src/assets/Logos/`
- Place logo files in `public/Logos/`
- Use SVG format
- Import the SVG at the top of the file and reference the imported variable:
```ts
import myServiceUrl from '@/assets/Logos/my-service.svg';
// then in the config object:
imgUrl: myServiceUrl,
```
- Reference as `"/Logos/your-logo.svg"`
- **Fetching Icons**: New icons can be easily fetched from [OpenBrand](https://openbrand.sh/). Use the pattern `https://openbrand.sh/?url=<TARGET_URL>`, where `<TARGET_URL>` is the URL-encoded link to the service's website. For example, to get Render's logo, use [https://openbrand.sh/?url=https%3A%2F%2Frender.com](https://openbrand.sh/?url=https%3A%2F%2Frender.com).
- **Optimize new SVGs**: Run any newly downloaded SVGs through an optimizer like [SVGOMG (svgo)](https://svgomg.net/) or use `npx svgo src/assets/Logos/your-logo.svg` to minimise their size before committing.
- **Optimize new SVGs**: Run any newly downloaded SVGs through an optimizer like [SVGOMG (svgo)](https://svgomg.net/) or use `npx svgo public/Logos/your-logo.svg` to minimise their size before committing.
### 4. Links
@@ -302,8 +290,8 @@ import ec2Url from '@/assets/Logos/ec2.svg';
## Adding a New Data Source
1. Add the logo SVG to `src/assets/Logos/` and add a top-level import in the config file (e.g., `import myServiceUrl from '@/assets/Logos/my-service.svg'`)
2. Add your data source object to the `onboardingConfigWithLinks` array, referencing the imported variable for `imgUrl`
1. Add your data source object to the JSON array
2. Ensure the logo exists in `public/Logos/`
3. Test the flow locally with `yarn dev`
4. Validation:
- Navigate to the [onboarding page](http://localhost:3301/get-started-with-signoz-cloud) on your local machine

5
frontend/.gitignore vendored
View File

@@ -28,4 +28,7 @@ e2e/test-plan/saved-views/
e2e/test-plan/service-map/
e2e/test-plan/services/
e2e/test-plan/traces/
e2e/test-plan/user-preferences/
e2e/test-plan/user-preferences/
# Generated by `vite build` — do not commit
index.html.gotmpl

View File

@@ -2,6 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<base href="[[.BasePath]]" />
<meta
http-equiv="Cache-Control"
content="no-cache, no-store, must-revalidate, max-age: 0"
@@ -59,7 +60,7 @@
<meta data-react-helmet="true" name="docusaurus_locale" content="en" />
<meta data-react-helmet="true" name="docusaurus_tag" content="default" />
<meta name="robots" content="noindex" />
<link data-react-helmet="true" rel="shortcut icon" href="/favicon.ico" />
<link data-react-helmet="true" rel="shortcut icon" href="favicon.ico" />
</head>
<body data-theme="default">
<noscript>You need to enable JavaScript to run this app.</noscript>
@@ -113,7 +114,7 @@
})(document, 'script');
}
</script>
<link rel="stylesheet" href="/css/uPlot.min.css" />
<link rel="stylesheet" href="css/uPlot.min.css" />
<script type="module" src="./src/index.tsx"></script>
</body>
</html>

View File

@@ -1,5 +1,6 @@
import {
interceptorRejected,
interceptorsRequestBasePath,
interceptorsRequestResponse,
interceptorsResponse,
} from 'api';
@@ -17,6 +18,7 @@ export const GeneratedAPIInstance = <T>(
return generatedAPIAxiosInstance({ ...config }).then(({ data }) => data);
};
generatedAPIAxiosInstance.interceptors.request.use(interceptorsRequestBasePath);
generatedAPIAxiosInstance.interceptors.request.use(interceptorsRequestResponse);
generatedAPIAxiosInstance.interceptors.response.use(
interceptorsResponse,

View File

@@ -11,6 +11,7 @@ import axios, {
import { ENVIRONMENT } from 'constants/env';
import { Events } from 'constants/events';
import { LOCALSTORAGE } from 'constants/localStorage';
import { getBasePath } from 'utils/getBasePath';
import { eventEmitter } from 'utils/getEventEmitter';
import apiV1, { apiAlertManager, apiV2, apiV3, apiV4, apiV5 } from './apiV1';
@@ -67,6 +68,28 @@ export const interceptorsRequestResponse = (
return value;
};
// Prepends the runtime base path to outgoing requests so API calls work under
// a URL prefix (e.g. /signoz/api/v1/…). No-op for root deployments and dev
// (dev baseURL is a full http:// URL, not an absolute path).
export const interceptorsRequestBasePath = (
value: InternalAxiosRequestConfig,
): InternalAxiosRequestConfig => {
const basePath = getBasePath();
if (basePath === '/') {
return value;
}
if (value.baseURL?.startsWith('/')) {
// Named instances: baseURL='/api/v1/' → '/signoz/api/v1/'
value.baseURL = basePath + value.baseURL.slice(1);
} else if (!value.baseURL && value.url?.startsWith('/')) {
// Generated instance: baseURL is '' in prod, path is in url
value.url = basePath + value.url.slice(1);
}
return value;
};
export const interceptorRejected = async (
value: AxiosResponse<any>,
): Promise<AxiosResponse<any>> => {
@@ -133,6 +156,7 @@ const instance = axios.create({
});
instance.interceptors.request.use(interceptorsRequestResponse);
instance.interceptors.request.use(interceptorsRequestBasePath);
instance.interceptors.response.use(interceptorsResponse, interceptorRejected);
export const AxiosAlertManagerInstance = axios.create({
@@ -147,6 +171,7 @@ ApiV2Instance.interceptors.response.use(
interceptorRejected,
);
ApiV2Instance.interceptors.request.use(interceptorsRequestResponse);
ApiV2Instance.interceptors.request.use(interceptorsRequestBasePath);
// axios V3
export const ApiV3Instance = axios.create({
@@ -158,6 +183,7 @@ ApiV3Instance.interceptors.response.use(
interceptorRejected,
);
ApiV3Instance.interceptors.request.use(interceptorsRequestResponse);
ApiV3Instance.interceptors.request.use(interceptorsRequestBasePath);
//
// axios V4
@@ -170,6 +196,7 @@ ApiV4Instance.interceptors.response.use(
interceptorRejected,
);
ApiV4Instance.interceptors.request.use(interceptorsRequestResponse);
ApiV4Instance.interceptors.request.use(interceptorsRequestBasePath);
//
// axios V5
@@ -182,6 +209,7 @@ ApiV5Instance.interceptors.response.use(
interceptorRejected,
);
ApiV5Instance.interceptors.request.use(interceptorsRequestResponse);
ApiV5Instance.interceptors.request.use(interceptorsRequestBasePath);
//
// axios Base
@@ -194,6 +222,7 @@ LogEventAxiosInstance.interceptors.response.use(
interceptorRejectedBase,
);
LogEventAxiosInstance.interceptors.request.use(interceptorsRequestResponse);
LogEventAxiosInstance.interceptors.request.use(interceptorsRequestBasePath);
//
AxiosAlertManagerInstance.interceptors.response.use(
@@ -201,6 +230,7 @@ AxiosAlertManagerInstance.interceptors.response.use(
interceptorRejected,
);
AxiosAlertManagerInstance.interceptors.request.use(interceptorsRequestResponse);
AxiosAlertManagerInstance.interceptors.request.use(interceptorsRequestBasePath);
export { apiV1 };
export default instance;

View File

@@ -25,8 +25,7 @@ export const REACT_QUERY_KEY = {
ALERT_RULE_TIMELINE_GRAPH: 'ALERT_RULE_TIMELINE_GRAPH',
GET_CONSUMER_LAG_DETAILS: 'GET_CONSUMER_LAG_DETAILS',
TOGGLE_ALERT_STATE: 'TOGGLE_ALERT_STATE',
GET_ALL_ALERTS: 'GET_ALL_ALERTS',
ALERT_RULES_CHART_PREVIEW: 'ALERT_RULES_CHART_PREVIEW',
GET_ALL_ALLERTS: 'GET_ALL_ALLERTS',
REMOVE_ALERT_RULE: 'REMOVE_ALERT_RULE',
DUPLICATE_ALERT_RULE: 'DUPLICATE_ALERT_RULE',
GET_HOST_LIST: 'GET_HOST_LIST',

View File

@@ -36,10 +36,7 @@ import useUrlQuery from 'hooks/useUrlQuery';
import createQueryParams from 'lib/createQueryParams';
import history from 'lib/history';
import { isUndefined } from 'lodash-es';
import { useAllErrorsQueryState } from 'pages/AllErrors/QueryStateContext';
import { useTimezone } from 'providers/Timezone';
import { useGlobalTimeStore } from 'store/globalTime';
import { getAutoRefreshQueryKey } from 'store/globalTime/utils';
import { AppState } from 'store/reducers';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { Exception, PayloadProps } from 'types/api/errors/getAll';
@@ -73,11 +70,9 @@ type QueryParams = {
};
function AllErrors(): JSX.Element {
const { loading } = useSelector<AppState, GlobalReducer>(
const { maxTime, minTime, loading } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
const selectedTime = useGlobalTimeStore((s) => s.selectedTime);
const getMinMaxTime = useGlobalTimeStore((s) => s.getMinMaxTime);
const { pathname } = useLocation();
const params = useUrlQuery();
const { t } = useTranslation(['common']);
@@ -126,22 +121,11 @@ function AllErrors(): JSX.Element {
const { queries } = useResourceAttribute();
const compositeData = useGetCompositeQueryParam();
const setIsFetching = useAllErrorsQueryState((s) => s.setIsFetching);
const [
{ isLoading, isFetching: isErrorsFetching, data },
errorCountResponse,
] = useQueries([
const [{ isLoading, data }, errorCountResponse] = useQueries([
{
queryKey: getAutoRefreshQueryKey(
selectedTime,
'getAllErrors',
updatedPath,
compositeData,
),
queryFn: (): Promise<SuccessResponse<PayloadProps> | ErrorResponse> => {
const { minTime, maxTime } = getMinMaxTime();
return getAll({
queryKey: ['getAllErrors', updatedPath, maxTime, minTime, compositeData],
queryFn: (): Promise<SuccessResponse<PayloadProps> | ErrorResponse> =>
getAll({
end: maxTime,
start: minTime,
order: updatedOrder,
@@ -153,21 +137,20 @@ function AllErrors(): JSX.Element {
tags: convertCompositeQueryToTraceSelectedTags(
compositeData?.builder.queryData?.[0]?.filters?.items || [],
),
});
},
}),
enabled: !loading,
},
{
queryKey: getAutoRefreshQueryKey(
selectedTime,
queryKey: [
'getErrorCounts',
maxTime,
minTime,
getUpdatedExceptionType,
getUpdatedServiceName,
compositeData,
),
queryFn: (): Promise<ErrorResponse | SuccessResponse<number>> => {
const { minTime, maxTime } = getMinMaxTime();
return getErrorCounts({
],
queryFn: (): Promise<ErrorResponse | SuccessResponse<number>> =>
getErrorCounts({
end: maxTime,
start: minTime,
exceptionType: getUpdatedExceptionType,
@@ -175,17 +158,10 @@ function AllErrors(): JSX.Element {
tags: convertCompositeQueryToTraceSelectedTags(
compositeData?.builder.queryData?.[0]?.filters?.items || [],
),
});
},
}),
enabled: !loading,
},
]);
const isFetching = isErrorsFetching || errorCountResponse.isFetching;
useEffect(() => {
setIsFetching(isFetching);
}, [isFetching, setIsFetching]);
const { notifications } = useNotifications();
useEffect(() => {

View File

@@ -1,15 +1,12 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useQueryClient } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { LoadingOutlined } from '@ant-design/icons';
import { Spin, Table } from 'antd';
import logEvent from 'api/common/logEvent';
import emptyStateUrl from 'assets/Icons/emptyState.svg';
import cx from 'classnames';
import QuerySearch from 'components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch';
import { initialQueriesMap } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import RightToolbarActions from 'container/QueryBuilder/components/ToolbarActions/RightToolbarActions';
import Toolbar from 'container/Toolbar/Toolbar';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
@@ -26,6 +23,8 @@ import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
import DOCLINKS from 'utils/docLinks';
import emptyStateUrl from '@/assets/Icons/emptyState.svg';
import { ApiMonitoringHardcodedAttributeKeys } from '../../constants';
import { DEFAULT_PARAMS, useApiMonitoringParams } from '../../queryParams';
import { columnsConfig, formatDataForTable } from '../../utils';
@@ -41,7 +40,6 @@ function DomainList(): JSX.Element {
(state) => state.globalTime,
);
const queryClient = useQueryClient();
const { currentQuery, handleRunQuery } = useQueryBuilder();
const query = useMemo(() => currentQuery?.builder?.queryData[0] || null, [
currentQuery,
@@ -55,10 +53,6 @@ function DomainList(): JSX.Element {
const compositeData = useGetCompositeQueryParam();
const handleCancelQuery = useCallback(() => {
queryClient.cancelQueries([REACT_QUERY_KEY.GET_DOMAINS_LIST]);
}, [queryClient]);
const { data, isLoading, isFetching } = useListOverview({
start: minTime,
end: maxTime,
@@ -125,13 +119,7 @@ function DomainList(): JSX.Element {
<section className={cx('api-module-right-section')}>
<Toolbar
showAutoRefresh={false}
rightActions={
<RightToolbarActions
onStageRunQuery={handleRunQuery}
isLoadingQueries={isFetching}
handleCancelQuery={handleCancelQuery}
/>
}
rightActions={<RightToolbarActions onStageRunQuery={handleRunQuery} />}
/>
<div className={cx('api-monitoring-list-header')}>
<QuerySearch

View File

@@ -18,16 +18,9 @@ import { GlobalReducer } from 'types/reducer/globalTime';
export interface ChartPreviewProps {
alertDef: AlertDef;
source?: YAxisSource;
isCancelled?: boolean;
onFetchingStateChange?: (isFetching: boolean) => void;
}
function ChartPreview({
alertDef,
source,
isCancelled = false,
onFetchingStateChange,
}: ChartPreviewProps): JSX.Element {
function ChartPreview({ alertDef, source }: ChartPreviewProps): JSX.Element {
const { currentQuery, panelType, stagedQuery } = useQueryBuilder();
const {
alertType,
@@ -95,8 +88,6 @@ function ChartPreview({
graphType={panelType || PANEL_TYPES.TIME_SERIES}
setQueryStatus={setQueryStatus}
additionalThresholds={thresholdState.thresholds}
isCancelled={isCancelled}
onFetchingStateChange={onFetchingStateChange}
/>
);
@@ -111,8 +102,6 @@ function ChartPreview({
graphType={panelType || PANEL_TYPES.TIME_SERIES}
setQueryStatus={setQueryStatus}
additionalThresholds={thresholdState.thresholds}
isCancelled={isCancelled}
onFetchingStateChange={onFetchingStateChange}
/>
);

View File

@@ -1,11 +1,9 @@
import { useCallback, useMemo, useState } from 'react';
import { useQueryClient } from 'react-query';
import { useCallback, useMemo } from 'react';
import { Button } from 'antd';
import classNames from 'classnames';
import { YAxisSource } from 'components/YAxisUnitSelector/types';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import QuerySectionComponent from 'container/FormAlertRules/QuerySection';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getMetricNameFromQueryData } from 'hooks/useGetYAxisUnit';
@@ -64,17 +62,7 @@ function QuerySection(): JSX.Element {
return currentQueryKey !== stagedQueryKey;
}, [currentQuery, alertType, thresholdState, stagedQuery]);
const queryClient = useQueryClient();
const [isLoadingQueries, setIsLoadingQueries] = useState(false);
const [isCancelled, setIsCancelled] = useState(false);
const handleCancelQuery = useCallback(() => {
queryClient.cancelQueries([REACT_QUERY_KEY.ALERT_RULES_CHART_PREVIEW]);
setIsCancelled(true);
}, [queryClient]);
const runQueryHandler = useCallback(() => {
setIsCancelled(false);
queryClient.invalidateQueries([REACT_QUERY_KEY.ALERT_RULES_CHART_PREVIEW]);
// Reset the source param when the query is changed
// Then manually run the query
if (source === YAxisSource.DASHBOARDS && didQueryChange) {
@@ -88,7 +76,6 @@ function QuerySection(): JSX.Element {
currentQuery,
didQueryChange,
handleRunQuery,
queryClient,
redirectWithQueryBuilderData,
source,
]);
@@ -119,12 +106,7 @@ function QuerySection(): JSX.Element {
return (
<div className="query-section">
<Stepper stepNumber={1} label="Define the query" />
<ChartPreview
alertDef={alertDef}
source={source}
isCancelled={isCancelled}
onFetchingStateChange={setIsLoadingQueries}
/>
<ChartPreview alertDef={alertDef} source={source} />
<div className="query-section-tabs">
<div className="query-section-query-actions">
{tabs.map((tab) => (
@@ -148,8 +130,6 @@ function QuerySection(): JSX.Element {
setQueryCategory={onQueryCategoryChange}
alertType={alertType}
runQuery={runQueryHandler}
isLoadingQueries={isLoadingQueries}
handleCancelQuery={handleCancelQuery}
alertDef={alertDef}
panelType={PANEL_TYPES.TIME_SERIES}
key={currentQuery.queryType}

View File

@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
// eslint-disable-next-line no-restricted-imports
import { useDispatch } from 'react-redux';
import { useDispatch, useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import Spinner from 'components/Spinner';
@@ -10,7 +10,6 @@ import { ENTITY_VERSION_V5 } from 'constants/app';
import { FeatureKeys } from 'constants/features';
import { QueryParams } from 'constants/query';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import AnomalyAlertEvaluationView from 'container/AnomalyAlertEvaluationView';
import { INITIAL_CRITICAL_THRESHOLD } from 'container/CreateAlertV2/context/constants';
import { Threshold } from 'container/CreateAlertV2/context/types';
@@ -37,14 +36,14 @@ import { isEmpty } from 'lodash-es';
import { useAppContext } from 'providers/App/App';
import { useTimezone } from 'providers/Timezone';
import { UpdateTimeInterval } from 'store/actions';
import { useGlobalTimeStore } from 'store/globalTime';
import { getAutoRefreshQueryKey } from 'store/globalTime/utils';
import { AppState } from 'store/reducers';
import { Warning } from 'types/api';
import { AlertDef } from 'types/api/alerts/def';
import { LegendPosition } from 'types/api/dashboard/getAll';
import APIError from 'types/api/error';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { GlobalReducer } from 'types/reducer/globalTime';
import uPlot from 'uplot';
import { getGraphType } from 'utils/getGraphType';
import { getSortedSeriesData } from 'utils/getSortedSeriesData';
@@ -70,8 +69,6 @@ export interface ChartPreviewProps {
setQueryStatus?: (status: string) => void;
showSideLegend?: boolean;
additionalThresholds?: Threshold[];
isCancelled?: boolean;
onFetchingStateChange?: (isFetching: boolean) => void;
}
// eslint-disable-next-line sonarjs/cognitive-complexity
@@ -89,8 +86,6 @@ function ChartPreview({
setQueryStatus,
showSideLegend = false,
additionalThresholds,
isCancelled = false,
onFetchingStateChange,
}: ChartPreviewProps): JSX.Element | null {
const { t } = useTranslation('alerts');
const dispatch = useDispatch();
@@ -122,7 +117,10 @@ function ChartPreview({
});
const { currentQuery } = useQueryBuilder();
const globalSelectedInterval = useGlobalTimeStore((s) => s.selectedTime);
const { minTime, maxTime, selectedTime: globalSelectedInterval } = useSelector<
AppState,
GlobalReducer
>((state) => state.globalTime);
const { featureFlags } = useAppContext();
@@ -186,22 +184,18 @@ function ChartPreview({
// alertDef?.version || DEFAULT_ENTITY_VERSION,
ENTITY_VERSION_V5,
{
queryKey: getAutoRefreshQueryKey(
globalSelectedInterval,
REACT_QUERY_KEY.ALERT_RULES_CHART_PREVIEW,
queryKey: [
'chartPreview',
userQueryKey || JSON.stringify(query),
selectedInterval,
minTime,
maxTime,
alertDef?.ruleType,
),
],
enabled: canQuery,
keepPreviousData: true,
},
);
useEffect(() => {
onFetchingStateChange?.(queryResponse.isFetching);
}, [queryResponse.isFetching, onFetchingStateChange]);
const graphRef = useRef<HTMLDivElement>(null);
useEffect((): void => {
@@ -211,7 +205,7 @@ function ChartPreview({
}
setMinTimeScale(startTime);
setMaxTimeScale(endTime);
}, [globalSelectedInterval, queryResponse, setQueryStatus]);
}, [maxTime, minTime, globalSelectedInterval, queryResponse, setQueryStatus]);
// Initialize graph visibility from localStorage
useEffect(() => {
@@ -344,9 +338,7 @@ function ChartPreview({
alertDef?.ruleType === AlertDetectionTypes.ANOMALY_DETECTION_ALERT;
const chartDataAvailable =
chartData &&
!queryResponse.isLoading &&
(!queryResponse.isError || isCancelled);
chartData && !queryResponse.isError && !queryResponse.isLoading;
const isAnomalyDetectionEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.ANOMALY_DETECTION)
@@ -367,7 +359,7 @@ function ChartPreview({
{queryResponse.isLoading && (
<Spinner size="large" tip="Loading..." height="100%" />
)}
{(queryResponse?.isError || queryResponse?.error) && !isCancelled && (
{(queryResponse?.isError || queryResponse?.error) && (
<ErrorInPlace error={queryResponse.error as APIError} />
)}
@@ -411,8 +403,6 @@ ChartPreview.defaultProps = {
setQueryStatus: (): void => {},
showSideLegend: false,
additionalThresholds: undefined,
isCancelled: false,
onFetchingStateChange: undefined,
};
export default ChartPreview;

View File

@@ -29,8 +29,6 @@ function QuerySection({
setQueryCategory,
alertType,
runQuery,
isLoadingQueries,
handleCancelQuery,
alertDef,
panelType,
ruleId,
@@ -178,8 +176,6 @@ function QuerySection({
queryType: queryCategory,
});
}}
handleCancelQuery={handleCancelQuery}
isLoadingQueries={isLoadingQueries}
/>
</span>
}
@@ -199,11 +195,7 @@ function QuerySection({
onChange={handleQueryCategoryChange}
tabBarExtraContent={
<span style={{ display: 'flex', gap: '1rem', alignItems: 'center' }}>
<RunQueryBtn
onStageRunQuery={runQuery}
handleCancelQuery={handleCancelQuery}
isLoadingQueries={isLoadingQueries}
/>
<RunQueryBtn onStageRunQuery={runQuery} />
</span>
}
items={items}
@@ -245,8 +237,6 @@ interface QuerySectionProps {
setQueryCategory: (n: EQueryType) => void;
alertType: AlertTypes;
runQuery: VoidFunction;
isLoadingQueries: boolean;
handleCancelQuery: () => void;
alertDef: AlertDef;
panelType: PANEL_TYPES;
ruleId: string;

View File

@@ -127,13 +127,6 @@ function FormAlertRules({
// use query client
const ruleCache = useQueryClient();
const [isChartQueryCancelled, setIsChartQueryCancelled] = useState(false);
const [isLoadingAlertQuery, setIsLoadingAlertQuery] = useState(false);
const handleCancelAlertQuery = useCallback(() => {
ruleCache.cancelQueries([REACT_QUERY_KEY.AUTO_REFRESH_QUERY]);
setIsChartQueryCancelled(true);
}, [ruleCache]);
const isNewRule = !ruleId || isEmpty(ruleId);
@@ -720,8 +713,6 @@ function FormAlertRules({
yAxisUnit={yAxisUnit || ''}
graphType={panelType || PANEL_TYPES.TIME_SERIES}
setQueryStatus={setQueryStatus}
isCancelled={isChartQueryCancelled}
onFetchingStateChange={setIsLoadingAlertQuery}
/>
);
@@ -740,8 +731,6 @@ function FormAlertRules({
yAxisUnit={yAxisUnit || ''}
graphType={panelType || PANEL_TYPES.TIME_SERIES}
setQueryStatus={setQueryStatus}
isCancelled={isChartQueryCancelled}
onFetchingStateChange={setIsLoadingAlertQuery}
/>
);
@@ -924,13 +913,7 @@ function FormAlertRules({
queryCategory={currentQuery.queryType}
setQueryCategory={onQueryCategoryChange}
alertType={alertType || AlertTypes.METRICS_BASED_ALERT}
runQuery={(): void => {
setIsChartQueryCancelled(false);
ruleCache.invalidateQueries([REACT_QUERY_KEY.AUTO_REFRESH_QUERY]);
handleRunQuery();
}}
isLoadingQueries={isLoadingAlertQuery}
handleCancelQuery={handleCancelAlertQuery}
runQuery={(): void => handleRunQuery()}
alertDef={alertDef}
panelType={panelType || PANEL_TYPES.TIME_SERIES}
key={currentQuery.queryType}

View File

@@ -6,7 +6,6 @@ import React, {
useRef,
useState,
} from 'react';
import { useQueryClient } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux'; // old code, TODO: fix this correctly
import {
@@ -25,7 +24,6 @@ import WarningPopover from 'components/WarningPopover/WarningPopover';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { PanelMode } from 'container/DashboardContainer/visualization/panels/types';
import useDrilldown from 'container/GridCardLayout/GridCard/FullView/useDrilldown';
import { populateMultipleResults } from 'container/NewWidget/LeftContainer/WidgetGraph/util';
@@ -51,8 +49,6 @@ import {
selectIsDashboardLocked,
useDashboardStore,
} from 'providers/Dashboard/store/useDashboardStore';
import { useGlobalTimeStore } from 'store/globalTime';
import { getAutoRefreshQueryKey } from 'store/globalTime/utils';
import { AppState } from 'store/reducers';
import { Warning } from 'types/api';
import { GlobalReducer } from 'types/reducer/globalTime';
@@ -90,8 +86,6 @@ function FullView({
const fullViewRef = useRef<HTMLDivElement>(null);
const { handleRunQuery } = useQueryBuilder();
const queryClient = useQueryClient();
const selectedTimeFromStore = useGlobalTimeStore((s) => s.selectedTime);
useEffect(() => {
setCurrentGraphRef(fullViewRef);
@@ -209,34 +203,19 @@ function FullView({
});
}, [selectedPanelType]);
const queryRangeKey = useMemo(
() =>
getAutoRefreshQueryKey(
selectedTimeFromStore,
widget?.query,
selectedPanelType,
requestData,
version,
),
[
selectedTimeFromStore,
const response = useGetQueryRange(requestData, ENTITY_VERSION_V5, {
queryKey: [
widget?.query,
selectedPanelType,
requestData,
version,
minTime,
maxTime,
],
);
const response = useGetQueryRange(requestData, ENTITY_VERSION_V5, {
queryKey: queryRangeKey,
enabled: !isDependedDataLoaded,
keepPreviousData: true,
});
const handleCancelQuery = useCallback(() => {
queryClient.cancelQueries([REACT_QUERY_KEY.AUTO_REFRESH_QUERY]);
}, [queryClient]);
const onDragSelect = useCallback((start: number, end: number): void => {
const startTimestamp = Math.trunc(start);
const endTimestamp = Math.trunc(end);
@@ -375,8 +354,6 @@ function FullView({
onStageRunQuery={(): void => {
handleRunQuery();
}}
isLoadingQueries={response.isFetching}
handleCancelQuery={handleCancelQuery}
/>
</>
)}

View File

@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useQueryClient } from 'react-query';
import * as Sentry from '@sentry/react';
import { Button, Tooltip } from 'antd';
import logEvent from 'api/common/logEvent';
@@ -8,7 +7,6 @@ import { QueryBuilderV2 } from 'components/QueryBuilderV2/QueryBuilderV2';
import QuickFilters from 'components/QuickFilters/QuickFilters';
import { QuickFiltersSource, SignalType } from 'components/QuickFilters/types';
import { initialQueryMeterWithType, PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import ExplorerOptionWrapper from 'container/ExplorerOptions/ExplorerOptionWrapper';
import RightToolbarActions from 'container/QueryBuilder/components/ToolbarActions/RightToolbarActions';
import { QueryBuilderProps } from 'container/QueryBuilder/QueryBuilder.interfaces';
@@ -39,12 +37,6 @@ function Explorer(): JSX.Element {
currentQuery,
} = useQueryBuilder();
const { safeNavigate } = useSafeNavigate();
const queryClient = useQueryClient();
const [isLoadingQueries, setIsLoadingQueries] = useState(false);
const handleCancelQuery = useCallback(() => {
queryClient.cancelQueries([REACT_QUERY_KEY.AUTO_REFRESH_QUERY]);
}, [queryClient]);
const [showQuickFilters, setShowQuickFilters] = useState(true);
@@ -163,11 +155,7 @@ function Explorer(): JSX.Element {
<div className="explore-header-right-actions">
<DateTimeSelector showAutoRefresh />
<RightToolbarActions
onStageRunQuery={(): void => handleRunQuery()}
isLoadingQueries={isLoadingQueries}
handleCancelQuery={handleCancelQuery}
/>
<RightToolbarActions onStageRunQuery={(): void => handleRunQuery()} />
</div>
</div>
<QueryBuilderV2
@@ -183,7 +171,7 @@ function Explorer(): JSX.Element {
/>
<div className="explore-content">
<TimeSeries onFetchingStateChange={setIsLoadingQueries} />
<TimeSeries />
</div>
</div>
<ExplorerOptionWrapper

View File

@@ -0,0 +1,43 @@
import { Button } from 'antd';
import logEvent from 'api/common/logEvent';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { QueryBuilder } from 'container/QueryBuilder';
import { ButtonWrapper } from 'container/TracesExplorer/QuerySection/styles';
import { useGetPanelTypesQueryParam } from 'hooks/queryBuilder/useGetPanelTypesQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { DataSource } from 'types/common/queryBuilder';
import { MeterExplorerEventKeys, MeterExplorerEvents } from '../events';
function QuerySection(): JSX.Element {
const { handleRunQuery } = useQueryBuilder();
const panelTypes = useGetPanelTypesQueryParam(PANEL_TYPES.TIME_SERIES);
return (
<div className="query-section">
<QueryBuilder
panelType={panelTypes}
config={{ initialDataSource: DataSource.METRICS, queryVariant: 'static' }}
version="v4"
actions={
<ButtonWrapper>
<Button
onClick={(): void => {
handleRunQuery();
logEvent(MeterExplorerEvents.QueryBuilderQueryChanged, {
[MeterExplorerEventKeys.Tab]: 'explorer',
});
}}
type="primary"
>
Run Query
</Button>
</ButtonWrapper>
}
/>
</div>
);
}
export default QuerySection;

View File

@@ -1,5 +1,7 @@
import { useEffect, useMemo } from 'react';
import { useMemo } from 'react';
import { useQueries } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { isAxiosError } from 'axios';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { initialQueryMeterWithType, PANEL_TYPES } from 'constants/queryBuilder';
@@ -8,27 +10,25 @@ import EmptyMetricsSearch from 'container/MetricsExplorer/Explorer/EmptyMetricsS
import { BuilderUnitsFilter } from 'container/QueryBuilder/filters/BuilderUnitsFilter';
import TimeSeriesView from 'container/TimeSeriesView/TimeSeriesView';
import { convertDataValueToMs } from 'container/TimeSeriesView/utils';
import { Time } from 'container/TopNav/DateTimeSelectionV2/types';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import useUrlYAxisUnit from 'hooks/useUrlYAxisUnit';
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
import { useErrorModal } from 'providers/ErrorModalProvider';
import { useGlobalTimeStore } from 'store/globalTime';
import { getAutoRefreshQueryKey } from 'store/globalTime/utils';
import { AppState } from 'store/reducers';
import { SuccessResponse } from 'types/api';
import APIError from 'types/api/error';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
interface TimeSeriesProps {
onFetchingStateChange?: (isFetching: boolean) => void;
}
function TimeSeries({ onFetchingStateChange }: TimeSeriesProps): JSX.Element {
function TimeSeries(): JSX.Element {
const { stagedQuery, currentQuery } = useQueryBuilder();
const { yAxisUnit, onUnitChange } = useUrlYAxisUnit('');
const selectedTime = useGlobalTimeStore((s) => s.selectedTime);
const { selectedTime: globalSelectedTime, maxTime, minTime } = useSelector<
AppState,
GlobalReducer
>((state) => state.globalTime);
const isValidToConvertToMs = useMemo(() => {
const isValid: boolean[] = [];
@@ -58,38 +58,30 @@ function TimeSeries({ onFetchingStateChange }: TimeSeriesProps): JSX.Element {
const queries = useQueries(
queryPayloads.map((payload, index) => ({
queryKey: getAutoRefreshQueryKey(
selectedTime,
queryKey: [
REACT_QUERY_KEY.GET_QUERY_RANGE,
payload,
ENTITY_VERSION_V5,
globalSelectedTime,
maxTime,
minTime,
index,
),
queryFn: ({
signal,
}: {
signal?: AbortSignal;
}): Promise<SuccessResponse<MetricRangePayloadProps>> =>
],
queryFn: (): Promise<SuccessResponse<MetricRangePayloadProps>> =>
GetMetricQueryRange(
{
query: payload,
graphType: PANEL_TYPES.BAR,
selectedTime: 'GLOBAL_TIME',
globalSelectedInterval: selectedTime as Time,
globalSelectedInterval: globalSelectedTime,
params: {
dataSource: DataSource.METRICS,
},
},
ENTITY_VERSION_V5,
undefined,
signal,
),
enabled: !!payload,
retry: (failureCount: number, error: unknown): boolean => {
if (isAxiosError(error) && error.code === 'ERR_CANCELED') {
return false;
}
retry: (failureCount: number, error: Error): boolean => {
let status: number | undefined;
if (error instanceof APIError) {
@@ -110,11 +102,6 @@ function TimeSeries({ onFetchingStateChange }: TimeSeriesProps): JSX.Element {
})),
);
const isFetching = queries.some((q) => q.isFetching);
useEffect(() => {
onFetchingStateChange?.(isFetching);
}, [isFetching, onFetchingStateChange]);
const data = useMemo(() => queries.map(({ data }) => data) ?? [], [queries]);
const responseData = useMemo(

View File

@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useQueryClient } from 'react-query';
import { useSearchParams } from 'react-router-dom-v5-compat';
import * as Sentry from '@sentry/react';
import { Switch, Tooltip } from 'antd';
@@ -7,7 +6,6 @@ import logEvent from 'api/common/logEvent';
import { QueryBuilderV2 } from 'components/QueryBuilderV2/QueryBuilderV2';
import WarningPopover from 'components/WarningPopover/WarningPopover';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import ExplorerOptionWrapper from 'container/ExplorerOptions/ExplorerOptionWrapper';
import RightToolbarActions from 'container/QueryBuilder/components/ToolbarActions/RightToolbarActions';
import { QueryBuilderProps } from 'container/QueryBuilder/QueryBuilder.interfaces';
@@ -56,12 +54,6 @@ function Explorer(): JSX.Element {
const { handleExplorerTabChange } = useHandleExplorerTabChange();
const [isMetricDetailsOpen, setIsMetricDetailsOpen] = useState(false);
const queryClient = useQueryClient();
const [isLoadingQueries, setIsLoadingQueries] = useState(false);
const handleCancelQuery = useCallback(() => {
queryClient.cancelQueries([REACT_QUERY_KEY.AUTO_REFRESH_QUERY]);
}, [queryClient]);
const metricNames = useMemo(() => {
const currentMetricNames: string[] = [];
stagedQuery?.builder.queryData.forEach((query) => {
@@ -315,11 +307,7 @@ function Explorer(): JSX.Element {
<div className="explore-header-right-actions">
{!isEmpty(warning) && <WarningPopover warningData={warning} />}
<DateTimeSelector showAutoRefresh />
<RightToolbarActions
onStageRunQuery={(): void => handleRunQuery()}
isLoadingQueries={isLoadingQueries}
handleCancelQuery={handleCancelQuery}
/>
<RightToolbarActions onStageRunQuery={(): void => handleRunQuery()} />
</div>
</div>
<QueryBuilderV2
@@ -331,7 +319,6 @@ function Explorer(): JSX.Element {
/>
<div className="explore-content">
<TimeSeries
onFetchingStateChange={setIsLoadingQueries}
showOneChartPerQuery={showOneChartPerQuery}
setWarning={setWarning}
areAllMetricUnitsSame={areAllMetricUnitsSame}

View File

@@ -1,10 +1,7 @@
import { useCallback } from 'react';
import { useIsFetching, useQueryClient } from 'react-query';
import { Button } from 'antd';
import logEvent from 'api/common/logEvent';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { QueryBuilder } from 'container/QueryBuilder';
import RunQueryBtn from 'container/QueryBuilder/components/RunQueryBtn/RunQueryBtn';
import { ButtonWrapper } from 'container/TracesExplorer/QuerySection/styles';
import { useGetPanelTypesQueryParam } from 'hooks/queryBuilder/useGetPanelTypesQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
@@ -14,16 +11,9 @@ import { MetricsExplorerEventKeys, MetricsExplorerEvents } from '../events';
function QuerySection(): JSX.Element {
const { handleRunQuery } = useQueryBuilder();
const queryClient = useQueryClient();
const panelTypes = useGetPanelTypesQueryParam(PANEL_TYPES.TIME_SERIES);
const isLoadingQueries = useIsFetching([REACT_QUERY_KEY.GET_QUERY_RANGE]) > 0;
const handleCancelQuery = useCallback(() => {
queryClient.cancelQueries([REACT_QUERY_KEY.GET_QUERY_RANGE]);
}, [queryClient]);
return (
<div className="query-section">
<QueryBuilder
@@ -32,16 +22,17 @@ function QuerySection(): JSX.Element {
version="v4"
actions={
<ButtonWrapper>
<RunQueryBtn
onStageRunQuery={(): void => {
<Button
onClick={(): void => {
handleRunQuery();
logEvent(MetricsExplorerEvents.QueryBuilderQueryChanged, {
[MetricsExplorerEventKeys.Tab]: 'explorer',
});
}}
isLoadingQueries={isLoadingQueries}
handleCancelQuery={handleCancelQuery}
/>
type="primary"
>
Run Query
</Button>
</ButtonWrapper>
}
/>

View File

@@ -1,5 +1,7 @@
import { useEffect, useMemo } from 'react';
import { useMemo } from 'react';
import { useQueries, useQueryClient } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { Color } from '@signozhq/design-tokens';
import { toast } from '@signozhq/sonner';
import { Button, Tooltip, Typography } from 'antd';
@@ -16,16 +18,15 @@ import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import TimeSeriesView from 'container/TimeSeriesView/TimeSeriesView';
import { convertDataValueToMs } from 'container/TimeSeriesView/utils';
import { Time } from 'container/TopNav/DateTimeSelectionV2/types';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
import { AlertTriangle } from 'lucide-react';
import { useGlobalTimeStore } from 'store/globalTime';
import { getAutoRefreshQueryKey } from 'store/globalTime/utils';
import { AppState } from 'store/reducers';
import { SuccessResponse } from 'types/api';
import APIError from 'types/api/error';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
import EmptyMetricsSearch from './EmptyMetricsSearch';
import { TimeSeriesProps } from './types';
@@ -35,7 +36,6 @@ import {
} from './utils';
function TimeSeries({
onFetchingStateChange,
showOneChartPerQuery,
setWarning,
isMetricUnitsLoading,
@@ -49,7 +49,10 @@ function TimeSeries({
}: TimeSeriesProps): JSX.Element {
const { stagedQuery, currentQuery } = useQueryBuilder();
const selectedTime = useGlobalTimeStore((s) => s.selectedTime);
const { selectedTime: globalSelectedTime, maxTime, minTime } = useSelector<
AppState,
GlobalReducer
>((state) => state.globalTime);
const queryClient = useQueryClient();
const isValidToConvertToMs = useMemo(() => {
@@ -86,38 +89,31 @@ function TimeSeries({
const queries = useQueries(
queryPayloads.map((payload, index) => ({
queryKey: getAutoRefreshQueryKey(
selectedTime,
queryKey: [
REACT_QUERY_KEY.GET_QUERY_RANGE,
payload,
ENTITY_VERSION_V5,
globalSelectedTime,
maxTime,
minTime,
index,
),
queryFn: ({
signal,
}: {
signal?: AbortSignal;
}): Promise<SuccessResponse<MetricRangePayloadProps>> =>
],
queryFn: (): Promise<SuccessResponse<MetricRangePayloadProps>> =>
GetMetricQueryRange(
{
query: payload,
graphType: PANEL_TYPES.TIME_SERIES,
selectedTime: 'GLOBAL_TIME',
globalSelectedInterval: selectedTime as Time,
globalSelectedInterval: globalSelectedTime,
params: {
dataSource: DataSource.METRICS,
},
},
// ENTITY_VERSION_V4,
ENTITY_VERSION_V5,
undefined,
signal,
),
enabled: !!payload,
retry: (failureCount: number, error: unknown): boolean => {
if (isAxiosError(error) && error.code === 'ERR_CANCELED') {
return false;
}
retry: (failureCount: number, error: Error): boolean => {
let status: number | undefined;
if (error instanceof APIError) {
@@ -135,11 +131,6 @@ function TimeSeries({
})),
);
const isFetching = queries.some((q) => q.isFetching);
useEffect(() => {
onFetchingStateChange?.(isFetching);
}, [isFetching, onFetchingStateChange]);
const data = useMemo(() => queries.map(({ data }) => data) ?? [], [queries]);
const responseData = useMemo(

View File

@@ -3,7 +3,6 @@ import { MetricsexplorertypesMetricMetadataDTO } from 'api/generated/services/si
import { Warning } from 'types/api';
export interface TimeSeriesProps {
onFetchingStateChange?: (isFetching: boolean) => void;
showOneChartPerQuery: boolean;
setWarning: Dispatch<SetStateAction<Warning | undefined>>;
areAllMetricUnitsSame: boolean;

View File

@@ -1,11 +1,9 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useQueryClient } from 'react-query';
import * as Sentry from '@sentry/react';
import { Color } from '@signozhq/design-tokens';
import { Button, Drawer, Empty, Skeleton, Typography } from 'antd';
import logEvent from 'api/common/logEvent';
import { useGetMetricMetadata } from 'api/generated/services/metrics';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
import { useIsDarkMode } from 'hooks/useDarkMode';
@@ -111,21 +109,6 @@ function Inspect({
reset,
} = useInspectMetrics(appliedMetricName);
const [isCancelled, setIsCancelled] = useState(false);
// Auto-reset isCancelled when a new query starts fetching
useEffect(() => {
if (isInspectMetricsRefetching) {
setIsCancelled(false);
}
}, [isInspectMetricsRefetching]);
const queryClient = useQueryClient();
const handleCancelInspectQuery = useCallback(() => {
queryClient.cancelQueries(REACT_QUERY_KEY.GET_INSPECT_METRICS_DETAILS);
setIsCancelled(true);
}, [queryClient]);
const handleDispatchMetricInspectionOptions = useCallback(
(action: MetricInspectionAction): void => {
dispatchMetricInspectionOptions(action);
@@ -196,7 +179,7 @@ function Inspect({
);
}
if (isInspectMetricsError && !isCancelled) {
if (isInspectMetricsError) {
const errorMessage = 'Error loading inspect metrics.';
return (
@@ -215,13 +198,7 @@ function Inspect({
data-testid="inspect-metrics-empty"
className="inspect-metrics-fallback"
>
<Empty
description={
isCancelled
? 'Query was cancelled. Run the query to see results.'
: 'No time series found for this metric to inspect.'
}
/>
<Empty description="No time series found for this metric to inspect." />
</div>
);
}
@@ -257,14 +234,6 @@ function Inspect({
inspectMetricsTimeSeries={inspectMetricsTimeSeries}
currentQuery={currentQueryData}
setCurrentQuery={setCurrentQueryData}
isLoadingQueries={isInspectMetricsLoading || isInspectMetricsRefetching}
handleCancelQuery={handleCancelInspectQuery}
onRunQuery={(): void => {
setIsCancelled(false);
queryClient.invalidateQueries([
REACT_QUERY_KEY.GET_INSPECT_METRICS_DETAILS,
]);
}}
/>
</div>
<div className="inspect-metrics-content-second-col">
@@ -288,7 +257,6 @@ function Inspect({
isInspectMetricsLoading,
isInspectMetricsRefetching,
isInspectMetricsError,
isCancelled,
inspectMetricsTimeSeries,
aggregatedTimeSeries,
formattedInspectMetricsTimeSeries,

View File

@@ -20,22 +20,13 @@ function QueryBuilder({
inspectMetricsTimeSeries,
currentQuery,
setCurrentQuery,
isLoadingQueries,
handleCancelQuery,
onRunQuery,
}: QueryBuilderProps): JSX.Element {
const applyInspectionOptions = useCallback(() => {
onRunQuery?.();
setAppliedMetricName(currentMetricName ?? '');
dispatchMetricInspectionOptions({
type: 'APPLY_METRIC_INSPECTION_OPTIONS',
});
}, [
currentMetricName,
setAppliedMetricName,
dispatchMetricInspectionOptions,
onRunQuery,
]);
}, [currentMetricName, setAppliedMetricName, dispatchMetricInspectionOptions]);
return (
<div className="inspect-metrics-query-builder">
@@ -48,11 +39,7 @@ function QueryBuilder({
>
Query Builder
</Button>
<RunQueryBtn
onStageRunQuery={applyInspectionOptions}
handleCancelQuery={handleCancelQuery}
isLoadingQueries={isLoadingQueries}
/>
<RunQueryBtn onStageRunQuery={applyInspectionOptions} />
</div>
<Card className="inspect-metrics-query-builder-content">
<MetricNameSearch

View File

@@ -103,8 +103,6 @@ describe('QueryBuilder', () => {
filterExpression: '',
} as any,
setCurrentQuery: jest.fn(),
isLoadingQueries: false,
handleCancelQuery: jest.fn(),
};
beforeEach(() => {

View File

@@ -65,9 +65,6 @@ export interface QueryBuilderProps {
inspectMetricsTimeSeries: InspectMetricsSeries[];
currentQuery: IBuilderQuery;
setCurrentQuery: (query: IBuilderQuery) => void;
isLoadingQueries: boolean;
handleCancelQuery: () => void;
onRunQuery?: () => void;
}
export interface MetricNameSearchProps {

View File

@@ -1,8 +1,6 @@
import { useCallback, useEffect, useMemo, useReducer, useState } from 'react';
import { useQuery } from 'react-query';
import { inspectMetrics } from 'api/generated/services/metrics';
import { isAxiosError } from 'axios';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { themeColors } from 'constants/theme';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { generateColor } from 'lib/uPlotLib/utils/generateColor';
@@ -109,7 +107,7 @@ export function useInspectMetrics(
isRefetching: isInspectMetricsRefetching,
} = useQuery({
queryKey: [
REACT_QUERY_KEY.GET_INSPECT_METRICS_DETAILS,
'inspectMetrics',
metricName,
start,
end,
@@ -129,12 +127,6 @@ export function useInspectMetrics(
),
enabled: !!metricName,
keepPreviousData: true,
retry: (failureCount: number, error: Error): boolean => {
if (isAxiosError(error) && error.code === 'ERR_CANCELED') {
return false;
}
return failureCount < 3;
},
});
const inspectMetricsData = useMemo(

View File

@@ -12,8 +12,6 @@ function MetricsSearch({
currentQueryFilterExpression,
setCurrentQueryFilterExpression,
isLoading,
handleCancelQuery,
onRunQuery,
}: MetricsSearchProps): JSX.Element {
const handleOnChange = useCallback(
(expression: string): void => {
@@ -24,8 +22,7 @@ function MetricsSearch({
const handleStageAndRunQuery = useCallback(() => {
onChange(currentQueryFilterExpression);
onRunQuery?.();
}, [currentQueryFilterExpression, onChange, onRunQuery]);
}, [currentQueryFilterExpression, onChange]);
const handleRunQuery = useCallback(
(expression: string): void => {
@@ -56,7 +53,6 @@ function MetricsSearch({
<RunQueryBtn
onStageRunQuery={handleStageAndRunQuery}
isLoadingQueries={isLoading}
handleCancelQuery={handleCancelQuery}
/>
<div className="metrics-search-options">
<DateTimeSelectionV2

View File

@@ -4,7 +4,6 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useSelector } from 'react-redux'; // old code, TODO: fix this correctly
import { useSearchParams } from 'react-router-dom-v5-compat';
import * as Sentry from '@sentry/react';
import { Typography } from 'antd';
import logEvent from 'api/common/logEvent';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import {
@@ -18,7 +17,6 @@ import {
Querybuildertypesv5OrderByDTO,
Querybuildertypesv5OrderDirectionDTO,
} from 'api/generated/services/sigNoz.schemas';
import eyesEmojiUrl from 'assets/Images/eyesEmoji.svg';
import { convertExpressionToFilters } from 'components/QueryBuilderV2/utils';
import { initialQueriesMap } from 'constants/queryBuilder';
import { usePageSize } from 'container/InfraMonitoringK8s/utils';
@@ -106,8 +104,6 @@ function Summary(): JSX.Element {
setCurrentQueryFilterExpression,
] = useState<string>(appliedFilterExpression);
const [isCancelled, setIsCancelled] = useState<boolean>(false);
useEffect(() => {
setCurrentQueryFilterExpression(appliedFilterExpression);
}, [appliedFilterExpression]);
@@ -168,7 +164,6 @@ function Summary(): JSX.Element {
isLoading: isGetMetricsStatsLoading,
isError: isGetMetricsStatsError,
error: metricsStatsError,
reset: resetMetricsStats,
} = useGetMetricsStats();
const {
@@ -177,7 +172,6 @@ function Summary(): JSX.Element {
isLoading: isGetMetricsTreemapLoading,
isError: isGetMetricsTreemapError,
error: metricsTreemapError,
reset: resetMetricsTreemap,
} = useGetMetricsTreemap();
const metricsStatsApiError = useMemo(
@@ -202,40 +196,6 @@ function Summary(): JSX.Element {
});
}, [metricsTreemapQuery, getMetricsTreemap]);
const handleCancelQuery = useCallback(() => {
resetMetricsStats();
resetMetricsTreemap();
setCurrentQueryFilterExpression(appliedFilterExpression);
setIsCancelled(true);
}, [
resetMetricsStats,
resetMetricsTreemap,
setCurrentQueryFilterExpression,
appliedFilterExpression,
]);
const handleRunQuery = useCallback(() => {
setIsCancelled(false);
getMetricsStats({
data: {
...metricsListQuery,
filter: { expression: currentQueryFilterExpression },
},
});
getMetricsTreemap({
data: {
...metricsTreemapQuery,
filter: { expression: currentQueryFilterExpression },
},
});
}, [
getMetricsStats,
getMetricsTreemap,
metricsListQuery,
metricsTreemapQuery,
currentQueryFilterExpression,
]);
const handleFilterChange = useCallback(
(expression: string) => {
const newFilters: TagFilter = {
@@ -370,19 +330,11 @@ function Summary(): JSX.Element {
!isGetMetricsTreemapLoading &&
!isGetMetricsTreemapError;
const isLoadingQueries =
isGetMetricsStatsLoading || isGetMetricsTreemapLoading;
const showFullScreenLoading =
isLoadingQueries &&
(isGetMetricsStatsLoading || isGetMetricsTreemapLoading) &&
formattedMetricsData.length === 0 &&
!treeMapData?.data[heatmapView]?.length;
const showNoMetrics =
isMetricsListDataEmpty &&
isMetricsTreeMapDataEmpty &&
!appliedFilterExpression;
return (
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
<div className="metrics-explorer-summary-tab">
@@ -391,26 +343,13 @@ function Summary(): JSX.Element {
onChange={handleFilterChange}
currentQueryFilterExpression={currentQueryFilterExpression}
setCurrentQueryFilterExpression={setCurrentQueryFilterExpression}
isLoading={isLoadingQueries}
handleCancelQuery={handleCancelQuery}
onRunQuery={handleRunQuery}
isLoading={isGetMetricsStatsLoading || isGetMetricsTreemapLoading}
/>
{showFullScreenLoading ? (
<MetricsLoading />
) : isCancelled ? (
<div className="no-logs-container">
<div className="no-logs-container-content">
<img className="eyes-emoji" src={eyesEmojiUrl} alt="eyes emoji" />
<Typography className="no-logs-text">
Query cancelled.
<span className="sub-text">
{' '}
Click &quot;Run Query&quot; to load metrics.
</span>
</Typography>
</div>
</div>
) : showNoMetrics ? (
) : isMetricsListDataEmpty &&
isMetricsTreeMapDataEmpty &&
!appliedFilterExpression ? (
<NoLogs dataSource={DataSource.METRICS} />
) : (
<>

View File

@@ -33,8 +33,6 @@ export interface MetricsSearchProps {
currentQueryFilterExpression: string;
setCurrentQueryFilterExpression: (expression: string) => void;
isLoading: boolean;
handleCancelQuery: () => void;
onRunQuery: () => void;
}
export interface MetricsTreemapProps {

View File

@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo } from 'react';
import { QueryKey } from 'react-query';
import { Color } from '@signozhq/design-tokens';
import { Button, Tabs, Typography } from 'antd';
import logEvent from 'api/common/logEvent';
@@ -18,14 +19,14 @@ import { Atom, Terminal } from 'lucide-react';
import { Widgets } from 'types/api/dashboard/getAll';
import { EQueryType } from 'types/common/dashboard';
import ClickHouseQueryContainer from './QueryBuilder/clickHouse';
import ClickHouseQueryContainer from './QueryBuilder/ClickHouse';
import PromQLQueryContainer from './QueryBuilder/promQL';
import './QuerySection.styles.scss';
function QuerySection({
selectedGraph,
queryRangeKey,
isLoadingQueries,
handleCancelQuery,
selectedWidget,
dashboardVersion,
dashboardId,
@@ -178,7 +179,7 @@ function QuerySection({
label="Stage & Run Query"
onStageRunQuery={handleRunQuery}
isLoadingQueries={isLoadingQueries}
handleCancelQuery={handleCancelQuery}
queryRangeKey={queryRangeKey}
/>
</span>
}
@@ -190,8 +191,8 @@ function QuerySection({
interface QueryProps {
selectedGraph: PANEL_TYPES;
isLoadingQueries: boolean;
handleCancelQuery: () => void;
queryRangeKey?: QueryKey;
isLoadingQueries?: boolean;
selectedWidget: Widgets;
dashboardVersion?: string;
dashboardId?: string;

View File

@@ -1,12 +1,14 @@
import { memo, useCallback, useEffect, useMemo } from 'react';
import { useQueryClient } from 'react-query';
import { memo, useEffect } from 'react';
import { useMemo } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useGlobalTimeStore } from 'store/globalTime';
import { getAutoRefreshQueryKey } from 'store/globalTime/utils';
import { AppState } from 'store/reducers';
import { GlobalReducer } from 'types/reducer/globalTime';
import { WidgetGraphProps } from '../types';
import ExplorerColumnsRenderer from './ExplorerColumnsRenderer';
@@ -32,22 +34,21 @@ function LeftContainer({
isNewPanel = false,
}: WidgetGraphProps): JSX.Element {
const { stagedQuery } = useQueryBuilder();
const queryClient = useQueryClient();
const selectedTime = useGlobalTimeStore((s) => s.selectedTime);
const { selectedTime: globalSelectedInterval, minTime, maxTime } = useSelector<
AppState,
GlobalReducer
>((state) => state.globalTime);
const queryRangeKey = useMemo(
() =>
getAutoRefreshQueryKey(
selectedTime,
REACT_QUERY_KEY.GET_QUERY_RANGE,
requestData,
),
[selectedTime, requestData],
() => [
REACT_QUERY_KEY.GET_QUERY_RANGE,
globalSelectedInterval,
requestData,
minTime,
maxTime,
],
[globalSelectedInterval, requestData, minTime, maxTime],
);
const handleCancelQuery = useCallback(() => {
queryClient.cancelQueries([REACT_QUERY_KEY.AUTO_REFRESH_QUERY]);
}, [queryClient]);
const queryResponse = useGetQueryRange(requestData, ENTITY_VERSION_V5, {
enabled: !!stagedQuery,
queryKey: queryRangeKey,
@@ -74,8 +75,8 @@ function LeftContainer({
<QueryContainer className="query-section-left-container">
<QuerySection
selectedGraph={selectedGraph}
queryRangeKey={queryRangeKey}
isLoadingQueries={queryResponse.isFetching}
handleCancelQuery={handleCancelQuery}
selectedWidget={selectedWidget}
dashboardVersion={ENTITY_VERSION_V5}
dashboardId={selectedDashboard?.id}

View File

@@ -1,3 +1,5 @@
import { useCallback } from 'react';
import { QueryKey, useIsFetching, useQueryClient } from 'react-query';
import { Button } from 'antd';
import cx from 'classnames';
import {
@@ -10,23 +12,14 @@ import {
import { getUserOperatingSystem, UserOperatingSystem } from 'utils/getUserOS';
import './RunQueryBtn.scss';
type RunQueryBtnProps = {
interface RunQueryBtnProps {
className?: string;
label?: string;
disabled?: boolean;
} & (
| {
onStageRunQuery: () => void;
handleCancelQuery: () => void;
isLoadingQueries: boolean;
}
| {
onStageRunQuery?: never;
handleCancelQuery?: never;
isLoadingQueries?: never;
}
);
isLoadingQueries?: boolean;
handleCancelQuery?: () => void;
onStageRunQuery?: () => void;
queryRangeKey?: QueryKey;
}
function RunQueryBtn({
className,
@@ -34,17 +27,33 @@ function RunQueryBtn({
isLoadingQueries,
handleCancelQuery,
onStageRunQuery,
disabled,
queryRangeKey,
}: RunQueryBtnProps): JSX.Element {
const isMac = getUserOperatingSystem() === UserOperatingSystem.MACOS;
const isLoading = isLoadingQueries ?? false;
const queryClient = useQueryClient();
const isKeyFetchingCount = useIsFetching(
queryRangeKey as QueryKey | undefined,
);
const isLoading =
typeof isLoadingQueries === 'boolean'
? isLoadingQueries
: isKeyFetchingCount > 0;
const onCancel = useCallback(() => {
if (handleCancelQuery) {
return handleCancelQuery();
}
if (queryRangeKey) {
queryClient.cancelQueries(queryRangeKey);
}
}, [handleCancelQuery, queryClient, queryRangeKey]);
return isLoading ? (
<Button
type="default"
icon={<Loader2 size={14} className="loading-icon animate-spin" />}
className={cx('cancel-query-btn periscope-btn danger', className)}
onClick={handleCancelQuery}
onClick={onCancel}
>
Cancel
</Button>
@@ -52,7 +61,7 @@ function RunQueryBtn({
<Button
type="primary"
className={cx('run-query-btn periscope-btn primary', className)}
disabled={disabled}
disabled={isLoading || !onStageRunQuery}
onClick={onStageRunQuery}
icon={<Play size={14} />}
>

View File

@@ -1,8 +1,18 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
// frontend/src/container/QueryBuilder/components/RunQueryBtn/__tests__/RunQueryBtn.test.tsx
import { fireEvent, render, screen } from '@testing-library/react';
import RunQueryBtn from '../RunQueryBtn';
jest.mock('react-query', () => {
const actual = jest.requireActual('react-query');
return {
...actual,
useIsFetching: jest.fn(),
useQueryClient: jest.fn(),
};
});
import { useIsFetching, useQueryClient } from 'react-query';
// Mock OS util
jest.mock('utils/getUserOS', () => ({
getUserOperatingSystem: jest.fn(),
@@ -16,60 +26,79 @@ describe('RunQueryBtn', () => {
(getUserOperatingSystem as jest.Mock).mockReturnValue(
UserOperatingSystem.MACOS,
);
(useIsFetching as jest.Mock).mockReturnValue(0);
(useQueryClient as jest.Mock).mockReturnValue({
cancelQueries: jest.fn(),
});
});
test('renders run state and triggers on click', async () => {
const user = userEvent.setup();
test('uses isLoadingQueries prop over useIsFetching', () => {
// Simulate fetching but prop forces not loading
(useIsFetching as jest.Mock).mockReturnValue(1);
const onRun = jest.fn();
render(<RunQueryBtn onStageRunQuery={onRun} isLoadingQueries={false} />);
// Should show "Run Query" (not cancel)
const runBtn = screen.getByRole('button', { name: /run query/i });
expect(runBtn).toBeInTheDocument();
expect(runBtn).toBeEnabled();
});
test('fallback cancel: uses handleCancelQuery when no key provided', () => {
(useIsFetching as jest.Mock).mockReturnValue(0);
const cancelQueries = jest.fn();
(useQueryClient as jest.Mock).mockReturnValue({ cancelQueries });
const onCancel = jest.fn();
render(
<RunQueryBtn
onStageRunQuery={onRun}
handleCancelQuery={onCancel}
isLoadingQueries={false}
/>,
);
render(<RunQueryBtn isLoadingQueries handleCancelQuery={onCancel} />);
const cancelBtn = screen.getByRole('button', { name: /cancel/i });
fireEvent.click(cancelBtn);
expect(onCancel).toHaveBeenCalledTimes(1);
expect(cancelQueries).not.toHaveBeenCalled();
});
test('renders run state and triggers on click', () => {
const onRun = jest.fn();
render(<RunQueryBtn onStageRunQuery={onRun} />);
const btn = screen.getByRole('button', { name: /run query/i });
expect(btn).toBeEnabled();
await user.click(btn);
fireEvent.click(btn);
expect(onRun).toHaveBeenCalledTimes(1);
});
test('shows cancel state and calls handleCancelQuery', async () => {
const user = userEvent.setup();
const onRun = jest.fn();
const onCancel = jest.fn();
render(
<RunQueryBtn
onStageRunQuery={onRun}
handleCancelQuery={onCancel}
isLoadingQueries
/>,
);
const cancel = screen.getByRole('button', { name: /cancel/i });
await user.click(cancel);
expect(onCancel).toHaveBeenCalledTimes(1);
});
test('disabled when disabled prop is true', () => {
render(<RunQueryBtn disabled />);
test('disabled when onStageRunQuery is undefined', () => {
render(<RunQueryBtn />);
expect(screen.getByRole('button', { name: /run query/i })).toBeDisabled();
});
test('disabled when no props provided', () => {
render(<RunQueryBtn />);
expect(
screen.getByRole('button', { name: /run query/i }),
).toBeInTheDocument();
test('shows cancel state and calls handleCancelQuery', () => {
const onCancel = jest.fn();
render(<RunQueryBtn isLoadingQueries handleCancelQuery={onCancel} />);
const cancel = screen.getByRole('button', { name: /cancel/i });
fireEvent.click(cancel);
expect(onCancel).toHaveBeenCalledTimes(1);
});
test('derives loading from queryKey via useIsFetching and cancels via queryClient', () => {
(useIsFetching as jest.Mock).mockReturnValue(1);
const cancelQueries = jest.fn();
(useQueryClient as jest.Mock).mockReturnValue({ cancelQueries });
const queryKey = ['GET_QUERY_RANGE', '1h', { some: 'req' }, 1, 2];
render(<RunQueryBtn queryRangeKey={queryKey} />);
// Button switches to cancel state
const cancelBtn = screen.getByRole('button', { name: /cancel/i });
expect(cancelBtn).toBeInTheDocument();
// Clicking cancel calls cancelQueries with the key
fireEvent.click(cancelBtn);
expect(cancelQueries).toHaveBeenCalledWith(queryKey);
});
test('shows Command + CornerDownLeft on mac', () => {
const { container } = render(
<RunQueryBtn
onStageRunQuery={jest.fn()}
handleCancelQuery={jest.fn()}
isLoadingQueries={false}
/>,
<RunQueryBtn onStageRunQuery={(): void => {}} />,
);
expect(container.querySelector('.lucide-command')).toBeInTheDocument();
expect(
@@ -82,11 +111,7 @@ describe('RunQueryBtn', () => {
UserOperatingSystem.WINDOWS,
);
const { container } = render(
<RunQueryBtn
onStageRunQuery={jest.fn()}
handleCancelQuery={jest.fn()}
isLoadingQueries={false}
/>,
<RunQueryBtn onStageRunQuery={(): void => {}} />,
);
expect(container.querySelector('.lucide-chevron-up')).toBeInTheDocument();
expect(container.querySelector('.lucide-command')).not.toBeInTheDocument();
@@ -96,14 +121,8 @@ describe('RunQueryBtn', () => {
});
test('renders custom label when provided', () => {
render(
<RunQueryBtn
onStageRunQuery={jest.fn()}
handleCancelQuery={jest.fn()}
isLoadingQueries={false}
label="Stage & Run Query"
/>,
);
const onRun = jest.fn();
render(<RunQueryBtn onStageRunQuery={onRun} label="Stage & Run Query" />);
expect(
screen.getByRole('button', { name: /stage & run query/i }),
).toBeInTheDocument();

View File

@@ -1,4 +1,5 @@
import { useEffect } from 'react';
import { MutableRefObject, useEffect } from 'react';
import { useQueryClient } from 'react-query';
import { LogsExplorerShortcuts } from 'constants/shortcuts/logsExplorerShortcuts';
import { useKeyboardHotkeys } from 'hooks/hotkeys/useKeyboardHotkeys';
@@ -8,19 +9,23 @@ import './ToolbarActions.styles.scss';
interface RightToolbarActionsProps {
onStageRunQuery: () => void;
isLoadingQueries: boolean;
handleCancelQuery: () => void;
isLoadingQueries?: boolean;
listQueryKeyRef?: MutableRefObject<any>;
chartQueryKeyRef?: MutableRefObject<any>;
showLiveLogs?: boolean;
}
export default function RightToolbarActions({
onStageRunQuery,
isLoadingQueries,
handleCancelQuery,
listQueryKeyRef,
chartQueryKeyRef,
showLiveLogs,
}: RightToolbarActionsProps): JSX.Element {
const { registerShortcut, deregisterShortcut } = useKeyboardHotkeys();
const queryClient = useQueryClient();
useEffect(() => {
if (showLiveLogs) {
return;
@@ -37,11 +42,20 @@ export default function RightToolbarActions({
if (showLiveLogs) {
return (
<div className="right-toolbar-actions-container">
<RunQueryBtn disabled />
<RunQueryBtn />
</div>
);
}
const handleCancelQuery = (): void => {
if (listQueryKeyRef?.current) {
queryClient.cancelQueries(listQueryKeyRef.current);
}
if (chartQueryKeyRef?.current) {
queryClient.cancelQueries(chartQueryKeyRef.current);
}
};
return (
<div className="right-toolbar-actions-container">
<RunQueryBtn
@@ -54,5 +68,8 @@ export default function RightToolbarActions({
}
RightToolbarActions.defaultProps = {
isLoadingQueries: false,
listQueryKeyRef: null,
chartQueryKeyRef: null,
showLiveLogs: false,
};

View File

@@ -92,12 +92,7 @@ describe('ToolbarActions', () => {
const onStageRunQuery = jest.fn();
const { queryByText } = render(
<MockQueryClientProvider>
<RightToolbarActions
onStageRunQuery={onStageRunQuery}
isLoadingQueries={false}
handleCancelQuery={jest.fn()}
/>
,
<RightToolbarActions onStageRunQuery={onStageRunQuery} />,
</MockQueryClientProvider>,
);

View File

@@ -132,10 +132,6 @@ export const useGetQueryRange: UseGetQueryRange = (
return options.retry;
}
return (failureCount: number, error: Error): boolean => {
if (isAxiosError(error) && error.code === 'ERR_CANCELED') {
return false;
}
let status: number | undefined;
if (error instanceof APIError) {

View File

@@ -1,3 +1,4 @@
import { createBrowserHistory } from 'history';
import { getBasePath } from 'utils/getBasePath';
export default createBrowserHistory();
export default createBrowserHistory({ basename: getBasePath() });

View File

@@ -431,7 +431,7 @@ export const useAlertRuleDuplicate = ({
const params = useUrlQuery();
const { refetch } = useQuery(REACT_QUERY_KEY.GET_ALL_ALERTS, {
const { refetch } = useQuery(REACT_QUERY_KEY.GET_ALL_ALLERTS, {
queryFn: getAll,
cacheTime: 0,
});

View File

@@ -1,13 +0,0 @@
import { create } from 'zustand';
interface AllErrorsQueryState {
isFetching: boolean;
setIsFetching: (isFetching: boolean) => void;
}
export const useAllErrorsQueryState = create<AllErrorsQueryState>((set) => ({
isFetching: false,
setIsFetching: (isFetching): void => {
set({ isFetching });
},
}));

View File

@@ -1,5 +1,4 @@
import { useCallback, useState } from 'react';
import { useQueryClient } from 'react-query';
import { useState } from 'react';
import { useLocation } from 'react-router-dom';
import { FilterOutlined } from '@ant-design/icons';
import { Button, Tooltip } from 'antd';
@@ -12,7 +11,6 @@ import { QuickFiltersSource, SignalType } from 'components/QuickFilters/types';
import RouteTab from 'components/RouteTab';
import TypicalOverlayScrollbar from 'components/TypicalOverlayScrollbar/TypicalOverlayScrollbar';
import { LOCALSTORAGE } from 'constants/localStorage';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import RightToolbarActions from 'container/QueryBuilder/components/ToolbarActions/RightToolbarActions';
import ResourceAttributesFilterV2 from 'container/ResourceAttributeFilterV2/ResourceAttributesFilterV2';
import Toolbar from 'container/Toolbar/Toolbar';
@@ -21,19 +19,12 @@ import history from 'lib/history';
import { isNull } from 'lodash-es';
import { routes } from './config';
import { useAllErrorsQueryState } from './QueryStateContext';
import './AllErrors.styles.scss';
function AllErrors(): JSX.Element {
const { pathname } = useLocation();
const { handleRunQuery } = useQueryBuilder();
const queryClient = useQueryClient();
const isLoadingQueries = useAllErrorsQueryState((s) => s.isFetching);
const handleCancelQuery = useCallback(() => {
queryClient.cancelQueries([REACT_QUERY_KEY.AUTO_REFRESH_QUERY]);
}, [queryClient]);
const [showFilters, setShowFilters] = useState<boolean>(() => {
const localStorageValue = getLocalStorageKey(
@@ -86,11 +77,7 @@ function AllErrors(): JSX.Element {
}
rightActions={
<div className="right-toolbar-actions-container">
<RightToolbarActions
onStageRunQuery={handleRunQuery}
isLoadingQueries={isLoadingQueries}
handleCancelQuery={handleCancelQuery}
/>
<RightToolbarActions onStageRunQuery={handleRunQuery} />
<HeaderRightSection
enableAnnouncements={false}
enableShare

View File

@@ -2,6 +2,7 @@ import { useCallback } from 'react';
import { Button } from 'antd';
import ROUTES from 'constants/routes';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import history from 'lib/history';
import { Home, LifeBuoy } from 'lucide-react';
import { handleContactSupport } from 'pages/Integrations/utils';
@@ -11,8 +12,9 @@ import './ErrorBoundaryFallback.styles.scss';
function ErrorBoundaryFallback(): JSX.Element {
const handleReload = (): void => {
// Go to home page
window.location.href = ROUTES.HOME;
// Use history.push so the navigation stays within the base path prefix
// (window.location.href would strip any /signoz/ prefix).
history.push(ROUTES.HOME);
};
const { isCloudUser: isCloudUserVal } = useGetTenantLicense();

View File

@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useQueryClient } from 'react-query';
import * as Sentry from '@sentry/react';
import getLocalStorageKey from 'api/browser/localstorage/get';
import setLocalStorageApi from 'api/browser/localstorage/set';
@@ -76,16 +75,6 @@ function LogsExplorer(): JSX.Element {
const [isLoadingQueries, setIsLoadingQueries] = useState<boolean>(false);
const queryClient = useQueryClient();
const handleCancelQuery = useCallback(() => {
if (listQueryKeyRef.current) {
queryClient.cancelQueries(listQueryKeyRef.current);
}
if (chartQueryKeyRef.current) {
queryClient.cancelQueries(chartQueryKeyRef.current);
}
}, [queryClient]);
const [warning, setWarning] = useState<Warning | undefined>(undefined);
const handleChangeSelectedView = useCallback(
@@ -308,8 +297,9 @@ function LogsExplorer(): JSX.Element {
rightActions={
<RightToolbarActions
onStageRunQuery={(): void => handleRunQuery()}
listQueryKeyRef={listQueryKeyRef}
chartQueryKeyRef={chartQueryKeyRef}
isLoadingQueries={isLoadingQueries}
handleCancelQuery={handleCancelQuery}
showLiveLogs={showLiveLogs}
/>
}

View File

@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useQueryClient } from 'react-query';
import { useSearchParams } from 'react-router-dom-v5-compat';
import * as Sentry from '@sentry/react';
import { Card } from 'antd';
@@ -72,19 +71,12 @@ function TracesExplorer(): JSX.Element {
});
const [searchParams] = useSearchParams();
const queryClient = useQueryClient();
const listQueryKeyRef = useRef<any>();
// Get panel type from URL
const panelTypesFromUrl = useGetPanelTypesQueryParam(PANEL_TYPES.LIST);
const [isLoadingQueries, setIsLoadingQueries] = useState<boolean>(false);
const handleCancelQuery = useCallback(() => {
if (listQueryKeyRef.current) {
queryClient.cancelQueries(listQueryKeyRef.current);
}
}, [queryClient]);
const [selectedView, setSelectedView] = useState<ExplorerViews>(() =>
getExplorerViewFromUrl(searchParams, panelTypesFromUrl),
);
@@ -220,7 +212,7 @@ function TracesExplorer(): JSX.Element {
<RightToolbarActions
onStageRunQuery={(): void => handleRunQuery()}
isLoadingQueries={isLoadingQueries}
handleCancelQuery={handleCancelQuery}
listQueryKeyRef={listQueryKeyRef}
/>
}
/>

View File

@@ -0,0 +1,50 @@
import { getBasePath } from 'utils/getBasePath';
/**
* Contract tests for getBasePath().
*
* These lock down the exact DOM-reading contract so that any future change to
* the utility (or to how index.html injects the <base> tag) surfaces
* immediately as a test failure.
*/
describe('getBasePath', () => {
afterEach(() => {
// Remove any <base> elements added during the test.
document.head.querySelectorAll('base').forEach((el) => el.remove());
});
it('returns the href from the <base> tag when present', () => {
const base = document.createElement('base');
base.setAttribute('href', '/signoz/');
document.head.appendChild(base);
expect(getBasePath()).toBe('/signoz/');
});
it('returns "/" when no <base> tag exists in the document', () => {
expect(getBasePath()).toBe('/');
});
it('returns "/" when the <base> tag has no href attribute', () => {
const base = document.createElement('base');
document.head.appendChild(base);
expect(getBasePath()).toBe('/');
});
it('returns the href unchanged when it already has a trailing slash', () => {
const base = document.createElement('base');
base.setAttribute('href', '/my/nested/path/');
document.head.appendChild(base);
expect(getBasePath()).toBe('/my/nested/path/');
});
it('appends a trailing slash when the href is missing one', () => {
const base = document.createElement('base');
base.setAttribute('href', '/signoz');
document.head.appendChild(base);
expect(getBasePath()).toBe('/signoz/');
});
});

View File

@@ -0,0 +1,17 @@
/**
* Returns the base path for this SigNoz deployment by reading the
* `<base href>` element injected into index.html by the Go backend at
* serve time.
*
* Always returns a string ending with `/` (e.g. `/`, `/signoz/`).
* Falls back to `/` when no `<base>` element is present so the app
* behaves correctly in local Vite dev and unit-test environments.
*
* @internal — consume through `src/lib/history` and the axios interceptor;
* do not read `<base>` directly anywhere else in the codebase.
*/
export function getBasePath(): string {
const href = document.querySelector('base')?.getAttribute('href') ?? '/';
// Trailing slash is required for relative asset resolution and API prefixing.
return href.endsWith('/') ? href : `${href}/`;
}

View File

@@ -10,6 +10,18 @@ import { createHtmlPlugin } from 'vite-plugin-html';
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer';
import tsconfigPaths from 'vite-tsconfig-paths';
// In dev the Go backend is not involved, so replace the [[.BasePath]] placeholder
// with "/" so relative assets resolve correctly from the Vite dev server.
function devBasePathPlugin(): Plugin {
return {
name: 'dev-base-path',
apply: 'serve',
transformIndexHtml(html): string {
return html.replace('[[.BasePath]]', '/');
},
};
}
function rawMarkdownPlugin(): Plugin {
return {
name: 'raw-markdown',
@@ -32,6 +44,7 @@ export default defineConfig(
const plugins = [
tsconfigPaths(),
rawMarkdownPlugin(),
devBasePathPlugin(),
react(),
createHtmlPlugin({
inject: {
@@ -124,6 +137,7 @@ export default defineConfig(
'process.env.TUNNEL_DOMAIN': JSON.stringify(env.VITE_TUNNEL_DOMAIN),
'process.env.DOCS_BASE_URL': JSON.stringify(env.VITE_DOCS_BASE_URL),
},
base: './',
build: {
sourcemap: true,
outDir: 'build',