Skip to content

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.

chore(alert-history): use v2 apis (#12132)

Vinicius Lourençoee06d549e621
diff --git a/frontend/src/api/alerts/ruleStats.ts b/frontend/src/api/alerts/ruleStats.ts
deleted file mode 100644
index 2e09751e0f..0000000000
--- a/frontend/src/api/alerts/ruleStats.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import axios from 'api';
-import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
-import { AxiosError } from 'axios';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-import { AlertRuleStatsPayload } from 'types/api/alerts/def';
-import { RuleStatsProps } from 'types/api/alerts/ruleStats';
-
-const ruleStats = async (
- props: RuleStatsProps,
-): Promise<SuccessResponse<AlertRuleStatsPayload> | ErrorResponse> => {
- try {
- const response = await axios.post(`/rules/${props.id}/history/stats`, {
- start: props.start,
- end: props.end,
- });
-
- return {
- statusCode: 200,
- error: null,
- message: response.data.status,
- payload: response.data,
- };
- } catch (error) {
- return ErrorResponseHandler(error as AxiosError);
- }
-};
-
-export default ruleStats;
diff --git a/frontend/src/api/alerts/timelineGraph.ts b/frontend/src/api/alerts/timelineGraph.ts
deleted file mode 100644
index 8073943d72..0000000000
--- a/frontend/src/api/alerts/timelineGraph.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import axios from 'api';
-import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
-import { AxiosError } from 'axios';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-import { AlertRuleTimelineGraphResponsePayload } from 'types/api/alerts/def';
-import { GetTimelineGraphRequestProps } from 'types/api/alerts/timelineGraph';
-
-const timelineGraph = async (
- props: GetTimelineGraphRequestProps,
-): Promise<
- SuccessResponse<AlertRuleTimelineGraphResponsePayload> | ErrorResponse
-> => {
- try {
- const response = await axios.post(
- `/rules/${props.id}/history/overall_status`,
- {
- start: props.start,
- end: props.end,
- },
- );
-
- return {
- statusCode: 200,
- error: null,
- message: response.data.status,
- payload: response.data,
- };
- } catch (error) {
- return ErrorResponseHandler(error as AxiosError);
- }
-};
-
-export default timelineGraph;
diff --git a/frontend/src/api/alerts/timelineTable.ts b/frontend/src/api/alerts/timelineTable.ts
deleted file mode 100644
index 8d7f3edee7..0000000000
--- a/frontend/src/api/alerts/timelineTable.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import axios from 'api';
-import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
-import { AxiosError } from 'axios';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-import { AlertRuleTimelineTableResponsePayload } from 'types/api/alerts/def';
-import { GetTimelineTableRequestProps } from 'types/api/alerts/timelineTable';
-
-const timelineTable = async (
- props: GetTimelineTableRequestProps,
-): Promise<
- SuccessResponse<AlertRuleTimelineTableResponsePayload> | ErrorResponse
-> => {
- try {
- const response = await axios.post(`/rules/${props.id}/history/timeline`, {
- start: props.start,
- end: props.end,
- offset: props.offset,
- limit: props.limit,
- order: props.order,
- state: props.state,
- // TODO(shaheer): implement filters
- filters: props.filters,
- });
-
- return {
- statusCode: 200,
- error: null,
- message: response.data.status,
- payload: response.data,
- };
- } catch (error) {
- return ErrorResponseHandler(error as AxiosError);
- }
-};
-
-export default timelineTable;
diff --git a/frontend/src/api/alerts/topContributors.ts b/frontend/src/api/alerts/topContributors.ts
deleted file mode 100644
index 7d3f2baec1..0000000000
--- a/frontend/src/api/alerts/topContributors.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import axios from 'api';
-import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
-import { AxiosError } from 'axios';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-import { AlertRuleTopContributorsPayload } from 'types/api/alerts/def';
-import { TopContributorsProps } from 'types/api/alerts/topContributors';
-
-const topContributors = async (
- props: TopContributorsProps,
-): Promise<
- SuccessResponse<AlertRuleTopContributorsPayload> | ErrorResponse
-> => {
- try {
- const response = await axios.post(
- `/rules/${props.id}/history/top_contributors`,
- {
- start: props.start,
- end: props.end,
- },
- );
-
- return {
- statusCode: 200,
- error: null,
- message: response.data.status,
- payload: response.data,
- };
- } catch (error) {
- return ErrorResponseHandler(error as AxiosError);
- }
-};
-
-export default topContributors;
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx
index 0761e781bd..d006fea13e 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx
@@ -102,6 +102,15 @@ interface QuerySearchProps {
showFilterSuggestionsWithoutMetric?: boolean;
/** When set, the editor shows only the user expression; API/filter uses `initial AND (user)`. */
initialExpression?: string;
+ /** When set, replaces the generic value-suggestion API with a custom fetcher. */
+ valueSuggestionsOverride?: (
+ key: string,
+ searchText: string,
+ ) => Promise<{
+ stringValues: string[];
+ numberValues: number[];
+ complete: boolean;
+ }>;
}
function QuerySearch({
@@ -115,6 +124,7 @@ function QuerySearch({
showFilterSuggestionsWithoutMetric,
initialExpression,
metricNamespace,
+ valueSuggestionsOverride,
}: QuerySearchProps): JSX.Element {
const isDarkMode = useIsDarkMode();
const [valueSuggestions, setValueSuggestions] = useState<any[]>([]);
@@ -484,13 +494,24 @@ function QuerySearch({
const sanitizedSearchText = searchText ? searchText?.trim() : '';
try {
- const response = await getValueSuggestions({
- key,
- searchText: sanitizedSearchText,
- signal: dataSource,
- signalSource: signalSource as 'meter' | '',
- metricName: debouncedMetricName ?? undefined,
- });
+ const values = valueSuggestionsOverride
+ ? await valueSuggestionsOverride(key, sanitizedSearchText)
+ : await getValueSuggestions({
+ key,
+ searchText: sanitizedSearchText,
+ signal: dataSource,
+ signalSource: signalSource as 'meter' | '',
+ metricName: debouncedMetricName ?? undefined,
+ }).then((response) => {
+ const responseData = response.data as any;
+ const data = responseData.data || {};
+ const values = data.values || {};
+ return {
+ stringValues: values.stringValues || [],
+ numberValues: values.numberValues || [],
+ complete: data.complete ?? false,
+ };
+ });
// Skip updates if component unmounted or key changed
if (
@@ -502,8 +523,6 @@ function QuerySearch({
}
// Process the response data
- const responseData = response.data as any;
- const values = responseData.data?.values || {};
const stringValues = values.stringValues || [];
const numberValues = values.numberValues || [];
@@ -584,6 +603,7 @@ function QuerySearch({
debouncedMetricName,
signalSource,
toggleSuggestions,
+ valueSuggestionsOverride,
],
);
diff --git a/frontend/src/constants/reactQueryKeys.ts b/frontend/src/constants/reactQueryKeys.ts
index f89f0b7466..d23a0de085 100644
--- a/frontend/src/constants/reactQueryKeys.ts
+++ b/frontend/src/constants/reactQueryKeys.ts
@@ -20,10 +20,6 @@ export const REACT_QUERY_KEY = {
DELETE_DASHBOARD: 'DELETE_DASHBOARD',
LOGS_PIPELINE_PREVIEW: 'LOGS_PIPELINE_PREVIEW',
ALERT_RULE_DETAILS: 'ALERT_RULE_DETAILS',
- ALERT_RULE_STATS: 'ALERT_RULE_STATS',
- ALERT_RULE_TOP_CONTRIBUTORS: 'ALERT_RULE_TOP_CONTRIBUTORS',
- ALERT_RULE_TIMELINE_TABLE: 'ALERT_RULE_TIMELINE_TABLE',
- 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',
diff --git a/frontend/src/container/AlertHistory/Statistics/StatsCardsRenderer/StatsCardsRenderer.tsx b/frontend/src/container/AlertHistory/Statistics/StatsCardsRenderer/StatsCardsRenderer.tsx
index 05f8c49e70..6f932e3a3e 100644
--- a/frontend/src/container/AlertHistory/Statistics/StatsCardsRenderer/StatsCardsRenderer.tsx
+++ b/frontend/src/container/AlertHistory/Statistics/StatsCardsRenderer/StatsCardsRenderer.tsx
@@ -1,6 +1,7 @@
-import { useEffect } from 'react';
+import { useEffect, useMemo } from 'react';
import { useGetAlertRuleDetailsStats } from 'pages/AlertDetails/hooks';
import DataStateRenderer from 'periscope/components/DataStateRenderer/DataStateRenderer';
+import { StatsTimeSeriesItem } from 'types/api/alerts/def';
import AverageResolutionCard from '../AverageResolutionCard/AverageResolutionCard';
import StatsCard from '../StatsCard/StatsCard';
@@ -25,24 +26,59 @@ type StatsCardsRendererProps = {
};
// TODO(shaheer): render the DataStateRenderer inside the TotalTriggeredCard/AverageResolutionCard, it should display the title
+type AdaptedStatsData = {
+ totalCurrentTriggers: number;
+ totalPastTriggers: number;
+ currentAvgResolutionTime: string;
+ pastAvgResolutionTime: string;
+ currentTriggersSeries: StatsTimeSeriesItem[];
+ currentAvgResolutionTimeSeries: StatsTimeSeriesItem[];
+};
+
function StatsCardsRenderer({
setTotalCurrentTriggers,
}: StatsCardsRendererProps): JSX.Element {
const { isLoading, isRefetching, isError, data, isValidRuleId, ruleId } =
useGetAlertRuleDetailsStats();
+ const adaptedData = useMemo((): AdaptedStatsData | null => {
+ if (!data?.data) {
+ return null;
+ }
+ const statsData = data.data;
+
+ const adaptTimeSeries = (
+ series: typeof statsData.currentTriggersSeries,
+ ): StatsTimeSeriesItem[] =>
+ series?.values?.map((item) => ({
+ timestamp: item.timestamp ?? 0,
+ value: String(item.value ?? 0),
+ })) ?? [];
+
+ return {
+ totalCurrentTriggers: statsData.totalCurrentTriggers,
+ totalPastTriggers: statsData.totalPastTriggers,
+ currentAvgResolutionTime: String(statsData.currentAvgResolutionTime),
+ pastAvgResolutionTime: String(statsData.pastAvgResolutionTime),
+ currentTriggersSeries: adaptTimeSeries(statsData.currentTriggersSeries),
+ currentAvgResolutionTimeSeries: adaptTimeSeries(
+ statsData.currentAvgResolutionTimeSeries,
+ ),
+ };
+ }, [data?.data]);
+
useEffect(() => {
- if (data?.payload?.data?.totalCurrentTriggers !== undefined) {
- setTotalCurrentTriggers(data.payload.data.totalCurrentTriggers);
+ if (adaptedData?.totalCurrentTriggers !== undefined) {
+ setTotalCurrentTriggers(adaptedData.totalCurrentTriggers);
}
- }, [data, setTotalCurrentTriggers]);
+ }, [adaptedData, setTotalCurrentTriggers]);
return (
<DataStateRenderer
isLoading={isLoading}
isRefetching={isRefetching}
isError={isError || !isValidRuleId || !ruleId}
- data={data?.payload?.data || null}
+ data={adaptedData}
>
{(data): JSX.Element => {
const {
@@ -60,7 +96,7 @@ function StatsCardsRenderer({
<TotalTriggeredCard
totalCurrentTriggers={totalCurrentTriggers}
totalPastTriggers={totalPastTriggers}
- timeSeries={currentTriggersSeries?.values}
+ timeSeries={currentTriggersSeries}
/>
) : (
<StatsCard
@@ -77,7 +113,7 @@ function StatsCardsRenderer({
<AverageResolutionCard
currentAvgResolutionTime={currentAvgResolutionTime}
pastAvgResolutionTime={pastAvgResolutionTime}
- timeSeries={currentAvgResolutionTimeSeries?.values}
+ timeSeries={currentAvgResolutionTimeSeries}
/>
) : (
<StatsCard
diff --git a/frontend/src/container/AlertHistory/Statistics/TopContributorsRenderer/TopContributorsRenderer.tsx b/frontend/src/container/AlertHistory/Statistics/TopContributorsRenderer/TopContributorsRenderer.tsx
index 55b438115b..7514bd394d 100644
--- a/frontend/src/container/AlertHistory/Statistics/TopContributorsRenderer/TopContributorsRenderer.tsx
+++ b/frontend/src/container/AlertHistory/Statistics/TopContributorsRenderer/TopContributorsRenderer.tsx
@@ -1,6 +1,8 @@
+import { useMemo } from 'react';
import { useGetAlertRuleDetailsTopContributors } from 'pages/AlertDetails/hooks';
+import { labelsArrayToObject } from 'container/AlertHistory/utils/labelAdapters';
import DataStateRenderer from 'periscope/components/DataStateRenderer/DataStateRenderer';
-import { AlertRuleStats } from 'types/api/alerts/def';
+import { AlertRuleStats, AlertRuleTopContributors } from 'types/api/alerts/def';
import TopContributorsCard from '../TopContributorsCard/TopContributorsCard';
@@ -13,15 +15,27 @@ function TopContributorsRenderer({
}: TopContributorsRendererProps): JSX.Element {
const { isLoading, isRefetching, isError, data, isValidRuleId, ruleId } =
useGetAlertRuleDetailsTopContributors();
- const response = data?.payload?.data;
// TODO(shaheer): render the DataStateRenderer inside the TopContributorsCard, it should display the title and view all
+ const adaptedData = useMemo((): AlertRuleTopContributors[] | null => {
+ if (!data?.data) {
+ return null;
+ }
+ return data.data.map((contributor) => ({
+ fingerprint: contributor.fingerprint,
+ count: contributor.count,
+ labels: labelsArrayToObject(contributor.labels),
+ relatedLogsLink: contributor.relatedLogsLink ?? '',
+ relatedTracesLink: contributor.relatedTracesLink ?? '',
+ }));
+ }, [data?.data]);
+
return (
<DataStateRenderer
isLoading={isLoading}
isRefetching={isRefetching}
isError={isError || !isValidRuleId || !ruleId}
- data={response || null}
+ data={adaptedData}
>
{(topContributorsData): JSX.Element => (
<TopContributorsCard
diff --git a/frontend/src/container/AlertHistory/Timeline/Graph/constants.ts b/frontend/src/container/AlertHistory/Timeline/Graph/constants.ts
index b56499a0d0..1584722419 100644
--- a/frontend/src/container/AlertHistory/Timeline/Graph/constants.ts
+++ b/frontend/src/container/AlertHistory/Timeline/Graph/constants.ts
@@ -1,12 +1,18 @@
import { Color } from '@signozhq/design-tokens';
+import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
-export const ALERT_STATUS: { [key: string]: number } = {
- firing: 0,
- inactive: 1,
+export const ALERT_STATUS: Record<RuletypesAlertStateDTO, number> & {
+ [key: string]: number;
+} = {
+ [RuletypesAlertStateDTO.firing]: 0,
+ [RuletypesAlertStateDTO.inactive]: 1,
normal: 1,
- 'no-data': 2,
- disabled: 3,
- muted: 4,
+ [RuletypesAlertStateDTO.pending]: 2,
+ [RuletypesAlertStateDTO.recovering]: 2,
+ 'no-data': 3,
+ [RuletypesAlertStateDTO.nodata]: 3,
+ [RuletypesAlertStateDTO.disabled]: 4,
+ muted: 5,
};
export const STATE_VS_COLOR: {
@@ -16,9 +22,10 @@ export const STATE_VS_COLOR: {
{
0: { stroke: Color.BG_CHERRY_500, fill: Color.BG_CHERRY_500 },
1: { stroke: Color.BG_FOREST_500, fill: Color.BG_FOREST_500 },
- 2: { stroke: Color.BG_SIENNA_400, fill: Color.BG_SIENNA_400 },
- 3: { stroke: Color.BG_VANILLA_400, fill: Color.BG_VANILLA_400 },
- 4: { stroke: Color.BG_INK_100, fill: Color.BG_INK_100 },
+ 2: { stroke: Color.BG_AMBER_500, fill: Color.BG_AMBER_500 },
+ 3: { stroke: Color.BG_SIENNA_400, fill: Color.BG_SIENNA_400 },
+ 4: { stroke: Color.BG_VANILLA_400, fill: Color.BG_VANILLA_400 },
+ 5: { stroke: Color.BG_INK_100, fill: Color.BG_INK_100 },
},
];
diff --git a/frontend/src/container/AlertHistory/Timeline/GraphWrapper/GraphWrapper.tsx b/frontend/src/container/AlertHistory/Timeline/GraphWrapper/GraphWrapper.tsx
index 530fa0d504..49bdf036a4 100644
--- a/frontend/src/container/AlertHistory/Timeline/GraphWrapper/GraphWrapper.tsx
+++ b/frontend/src/container/AlertHistory/Timeline/GraphWrapper/GraphWrapper.tsx
@@ -1,6 +1,8 @@
+import { useMemo } from 'react';
import useUrlQuery from 'hooks/useUrlQuery';
import { useGetAlertRuleDetailsTimelineGraphData } from 'pages/AlertDetails/hooks';
import DataStateRenderer from 'periscope/components/DataStateRenderer/DataStateRenderer';
+import { AlertRuleTimelineGraphResponse } from 'types/api/alerts/def';
import Graph from '../Graph/Graph';
@@ -18,26 +20,16 @@ function GraphWrapper({
const { isLoading, isRefetching, isError, data, isValidRuleId, ruleId } =
useGetAlertRuleDetailsTimelineGraphData();
- // TODO(shaheer): uncomment when the API is ready for
- // const { startTime } = useAlertHistoryQueryParams();
-
- // const [isVerticalGraph, setIsVerticalGraph] = useState(false);
-
- // useEffect(() => {
- // const checkVerticalGraph = (): void => {
- // if (startTime) {
- // const startTimeDate = dayjs(Number(startTime));
- // const twentyFourHoursAgo = dayjs().subtract(
- // HORIZONTAL_GRAPH_HOURS_THRESHOLD,
- // DAYJS_MANIPULATE_TYPES.HOUR,
- // );
-
- // setIsVerticalGraph(startTimeDate.isBefore(twentyFourHoursAgo));
- // }
- // };
-
- // checkVerticalGraph();
- // }, [startTime]);
+ const adaptedData = useMemo((): AlertRuleTimelineGraphResponse[] | null => {
+ if (!data?.data) {
+ return null;
+ }
+ return data.data.map((item) => ({
+ start: item.start,
+ end: item.end,
+ state: item.state as AlertRuleTimelineGraphResponse['state'],
+ }));
+ }, [data?.data]);
return (
<div className="timeline-graph">
@@ -49,7 +41,7 @@ function GraphWrapper({
isLoading={isLoading}
isError={isError || !isValidRuleId || !ruleId}
isRefetching={isRefetching}
- data={data?.payload?.data || null}
+ data={adaptedData}
>
{(data): JSX.Element => <Graph type="horizontal" data={data} />}
</DataStateRenderer>
diff --git a/frontend/src/container/AlertHistory/Timeline/Table/Table.styles.scss b/frontend/src/container/AlertHistory/Timeline/Table/Table.styles.scss
index 0b8d928978..31dc6609ab 100644
--- a/frontend/src/container/AlertHistory/Timeline/Table/Table.styles.scss
+++ b/frontend/src/container/AlertHistory/Timeline/Table/Table.styles.scss
@@ -1,11 +1,35 @@
.timeline-table {
border-top: 1px solid var(--l1-border);
border-radius: 6px;
- overflow: hidden;
margin-top: 4px;
min-height: 600px;
+
+ &__filter {
+ padding: 12px 16px;
+ background: var(--l1-background);
+ border-bottom: 1px solid var(--l1-border);
+ }
+
+ &__filter-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+
+ &__filter-search {
+ flex: 1;
+ }
+
+ &__filter--loading,
+ &__filter--loading-skeleton {
+ width: 100% !important;
+ }
+
.ant-table {
background: var(--l1-background);
+ &-placeholder {
+ background: var(--l1-background) !important;
+ }
&-cell {
padding: 12px 16px !important;
vertical-align: baseline;
@@ -23,6 +47,9 @@
&-tbody > tr > td {
border: none;
}
+ &-footer {
+ background-color: var(--l1-background);
+ }
}
.label-filter {
@@ -86,4 +113,38 @@
background: var(--l2-background);
}
}
+
+ &__error {
+ display: flex;
+ align-self: flex-start;
+ justify-content: flex-start;
+ text-align: left;
+ }
+
+ &__pagination {
+ display: flex;
+ justify-content: flex-end;
+ align-items: center;
+ gap: var(--spacing-4);
+ padding: var(--spacing-6) var(--spacing-8);
+ background: var(--l1-background);
+
+ .pagination-controls {
+ display: flex;
+ gap: 4px;
+
+ .ant-btn {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 4px;
+ min-width: 24px;
+ height: 24px;
+
+ &:disabled {
+ opacity: 0.4;
+ }
+ }
+ }
+ }
}
diff --git a/frontend/src/container/AlertHistory/Timeline/Table/Table.tsx b/frontend/src/container/AlertHistory/Timeline/Table/Table.tsx
index d9af13ceba..49a4089fee 100644
--- a/frontend/src/container/AlertHistory/Timeline/Table/Table.tsx
+++ b/frontend/src/container/AlertHistory/Timeline/Table/Table.tsx
@@ -1,52 +1,126 @@
-import { HTMLAttributes, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Table } from 'antd';
+import { HTMLAttributes, useCallback, useMemo } from 'react';
+import { Button, Skeleton, Table } from 'antd';
+import { ChevronLeft, ChevronRight } from '@signozhq/icons';
import logEvent from 'api/common/logEvent';
-import { initialFilters } from 'constants/queryBuilder';
+import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
+import ErrorContent from 'components/ErrorModal/components/ErrorContent';
+import {
+ QuerySearchV2Provider,
+ useExpression,
+ useInputExpression,
+ useQuerySearchOnChange,
+ useQuerySearchOnRun,
+} from 'components/QueryBuilderV2';
+import QuerySearch from 'components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch';
+import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
+import RunQueryBtn from 'container/QueryBuilder/components/RunQueryBtn/RunQueryBtn';
import {
useGetAlertRuleDetailsTimelineTable,
useTimelineTable,
} from 'pages/AlertDetails/hooks';
+import { labelsArrayToObject } from 'container/AlertHistory/utils/labelAdapters';
import { useTimezone } from 'providers/Timezone';
import { AlertRuleTimelineTableResponse } from 'types/api/alerts/def';
-import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
+import { DataSource } from 'types/common/queryBuilder';
+import { useAlertHistoryFilterSuggestions } from './useAlertHistoryFilterSuggestions';
import { timelineTableColumns } from './useTimelineTable';
import './Table.styles.scss';
-function TimelineTable(): JSX.Element {
- const [filters, setFilters] = useState<TagFilter>(initialFilters);
+export const ALERT_HISTORY_EXPRESSION_KEY = 'alertHistoryExpression';
+
+function TimelineTableContent(): JSX.Element {
+ const expression = useExpression();
+ const inputExpression = useInputExpression();
+ const querySearchOnChange = useQuerySearchOnChange();
+ const querySearchOnRun = useQuerySearchOnRun();
+
+ const {
+ isLoading,
+ isRefetching,
+ isError,
+ data,
+ error,
+ ruleId,
+ refetch,
+ cancel,
+ } = useGetAlertRuleDetailsTimelineTable({ filterExpression: expression });
+
+ const apiError = useMemo(() => convertToApiError(error), [error]);
- const { isLoading, isRefetching, isError, data, isValidRuleId, ruleId } =
- useGetAlertRuleDetailsTimelineTable({ filters });
+ const { hardcodedAttributeKeys, valueSuggestionsOverride, isLoadingKeys } =
+ useAlertHistoryFilterSuggestions(ruleId ?? null);
+
+ const { timelineData, totalItems, nextCursor } = useMemo(() => {
+ const response = data?.data;
+ const items: AlertRuleTimelineTableResponse[] | undefined =
+ response?.items?.map((item) => {
+ return {
+ ruleID: item.ruleId,
+ ruleName: item.ruleName,
+ overallState: item.overallState as string,
+ overallStateChanged: item.overallStateChanged,
+ state: item.state as string,
+ stateChanged: item.stateChanged,
+ unixMilli: item.unixMilli,
+ fingerprint: item.fingerprint,
+ value: item.value,
+ labels: labelsArrayToObject(item.labels),
+ relatedLogsLink: item.relatedLogsLink,
+ relatedTracesLink: item.relatedTracesLink,
+ };
+ });
- const { timelineData, totalItems, labels } = useMemo(() => {
- const response = data?.payload?.data;
return {
- timelineData: response?.items,
- totalItems: response?.total,
- labels: response?.labels,
+ timelineData: items,
+ totalItems: response?.total ?? 0,
+ nextCursor: response?.nextCursor,
};
- }, [data?.payload?.data]);
+ }, [data?.data]);
- const { paginationConfig, onChangeHandler } = useTimelineTable({
+ const {
+ paginationConfig,
+ onChangeHandler,
+ handleNextPage,
+ handlePrevPage,
+ hasNextPage,
+ hasPrevPage,
+ } = useTimelineTable({
totalItems: totalItems ?? 0,
+ nextCursor,
});
- const { t } = useTranslation('common');
-
const { formatTimezoneAdjustedTimestamp } = useTimezone();
- if (isError || !isValidRuleId || !ruleId) {
- return <div>{t('something_went_wrong')}</div>;
- }
+ const handleRunQuery = useCallback(
+ (updatedExpression?: string): void => {
+ const nextExpression = updatedExpression ?? inputExpression;
+ querySearchOnRun(nextExpression);
+
+ if (nextExpression === expression) {
+ refetch();
+ }
+ },
+ [querySearchOnRun, refetch, inputExpression, expression],
+ );
+
+ const queryData = useMemo(
+ () => ({
+ ...initialQueryBuilderFormValuesMap.logs,
+ queryName: 'A',
+ dataSource: DataSource.LOGS,
+ filter: { expression },
+ expression,
+ }),
+ [expression],
+ );
const handleRowClick = (
record: AlertRuleTimelineTableResponse,
): HTMLAttributes<AlertRuleTimelineTableResponse> => ({
onClick: (): void => {
- logEvent('Alert history: Timeline table row: Clicked', {
+ void logEvent('Alert history: Timeline table row: Clicked', {
ruleId: record.ruleID,
labels: record.labels,
});
@@ -55,23 +129,106 @@ function TimelineTable(): JSX.Element {
return (
<div className="timeline-table">
+ {/* If we don't wait to have the keys, the QuerySearch will not render them at first usage */}
+ {!isLoadingKeys && hardcodedAttributeKeys ? (
+ <div className="timeline-table__filter">
+ <div className="timeline-table__filter-row">
+ <div className="timeline-table__filter-search">
+ <QuerySearch
+ onChange={querySearchOnChange}
+ queryData={queryData}
+ dataSource={DataSource.LOGS}
+ onRun={handleRunQuery}
+ hardcodedAttributeKeys={hardcodedAttributeKeys}
+ valueSuggestionsOverride={valueSuggestionsOverride}
+ />
+ </div>
+ <RunQueryBtn
+ isLoadingQueries={isLoading || isRefetching}
+ onStageRunQuery={(): void => handleRunQuery()}
+ handleCancelQuery={cancel}
+ />
+ </div>
+ </div>
+ ) : (
+ <div className="timeline-table__filter timeline-table__filter--loading">
+ <Skeleton.Input
+ className="timeline-table__filter--loading-skeleton"
+ active
+ />
+ </div>
+ )}
<Table
rowKey={(row): string => `${row.fingerprint}-${row.value}-${row.unixMilli}`}
columns={timelineTableColumns({
- filters,
- labels: labels ?? {},
- setFilters,
formatTimezoneAdjustedTimestamp,
})}
onRow={handleRowClick}
dataSource={timelineData}
- pagination={paginationConfig}
+ pagination={false}
size="middle"
onChange={onChangeHandler}
loading={isLoading || isRefetching}
+ locale={{
+ emptyText:
+ isError && apiError ? (
+ <div className="timeline-table__error">
+ <ErrorContent error={apiError} />
+ </div>
+ ) : undefined,
+ }}
+ footer={(): JSX.Element => (
+ <div className="timeline-table__pagination">
+ <div className="timeline-table__pagination-info">
+ {paginationConfig.showTotal?.(totalItems, [
+ totalItems === 0
+ ? 0
+ : ((paginationConfig.current ?? 1) - 1) *
+ (paginationConfig.pageSize ?? 10) +
+ 1,
+ Math.min(
+ (paginationConfig.current ?? 1) * (paginationConfig.pageSize ?? 10),
+ totalItems,
+ ),
+ ])}
+ </div>
+ <div className="pagination-controls">
+ <Button
+ type="text"
+ size="small"
+ disabled={!hasPrevPage}
+ onClick={handlePrevPage}
+ data-testid="timeline-prev-page"
+ >
+ <ChevronLeft size={14} />
+ </Button>
+ <Button
+ type="text"
+ size="small"
+ disabled={!hasNextPage}
+ onClick={handleNextPage}
+ data-testid="timeline-next-page"
+ >
+ <ChevronRight size={14} />
+ </Button>
+ </div>
+ </div>
+ )}
/>
</div>
);
}
+function TimelineTable(): JSX.Element {
+ return (
+ <QuerySearchV2Provider
+ queryParamKey={ALERT_HISTORY_EXPRESSION_KEY}
+ initialExpression=""
+ persistOnUnmount
+ >
+ <TimelineTableContent />
+ </QuerySearchV2Provider>
+ );
+}
+
export default TimelineTable;
diff --git a/frontend/src/container/AlertHistory/Timeline/Table/useAlertHistoryFilterSuggestions.ts b/frontend/src/container/AlertHistory/Timeline/Table/useAlertHistoryFilterSuggestions.ts
new file mode 100644
index 0000000000..3273bfca1e
--- /dev/null
+++ b/frontend/src/container/AlertHistory/Timeline/Table/useAlertHistoryFilterSuggestions.ts
@@ -0,0 +1,100 @@
+import { useCallback, useMemo } from 'react';
+import {
+ getRuleHistoryFilterValues,
+ useGetRuleHistoryFilterKeys,
+} from 'api/generated/services/rules';
+import { useAlertHistoryQueryParams } from 'pages/AlertDetails/hooks';
+import { QueryKeyDataSuggestionsProps } from 'types/api/querySuggestions/types';
+import { fieldContextToSuggestionContext } from 'container/AlertHistory/Timeline/Table/utils';
+
+export interface AlertHistoryFilterSuggestions {
+ hardcodedAttributeKeys: QueryKeyDataSuggestionsProps[];
+ valueSuggestionsOverride: (
+ key: string,
+ searchText: string,
+ ) => Promise<{
+ stringValues: string[];
+ numberValues: number[];
+ complete: boolean;
+ }>;
+ isLoadingKeys: boolean;
+}
+
+export function useAlertHistoryFilterSuggestions(
+ ruleId: string | null,
+): AlertHistoryFilterSuggestions {
+ const { startTime, endTime } = useAlertHistoryQueryParams();
+
+ const { data: filterKeysData, isLoading: isLoadingKeys } =
+ useGetRuleHistoryFilterKeys(
+ { id: ruleId ?? '' },
+ { startUnixMilli: startTime, endUnixMilli: endTime },
+ {
+ query: {
+ enabled: !!ruleId,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ },
+ },
+ );
+
+ const hardcodedAttributeKeys = useMemo((): QueryKeyDataSuggestionsProps[] => {
+ const keys = filterKeysData?.data?.keys;
+ if (!keys) {
+ // by default, when QuerySearch keys fails, we don't render fallback keys
+ // we just return empty to let user write whatever they want with no
+ // key suggestion
+ return [];
+ }
+ return Object.values(keys).flatMap((items) =>
+ items.map(
+ (item) =>
+ ({
+ label: item.name,
+ name: item.name,
+ type: item.fieldDataType || 'string',
+ signal: 'logs' as const,
+ fieldDataType: item.fieldDataType,
+ fieldContext: fieldContextToSuggestionContext(item.fieldContext),
+ }) satisfies QueryKeyDataSuggestionsProps,
+ ),
+ );
+ }, [filterKeysData]);
+
+ const valueSuggestionsOverride = useCallback(
+ async (
+ key: string,
+ searchText: string,
+ ): Promise<{
+ stringValues: string[];
+ numberValues: number[];
+ complete: boolean;
+ }> => {
+ if (!ruleId) {
+ return {
+ stringValues: [],
+ numberValues: [],
+ complete: true,
+ };
+ }
+ const response = await getRuleHistoryFilterValues(
+ { id: ruleId },
+ {
+ name: key,
+ searchText,
+ startUnixMilli: startTime,
+ endUnixMilli: endTime,
+ },
+ );
+ const values = response.data?.values;
+ return {
+ stringValues: values?.stringValues ?? [],
+ numberValues: values?.numberValues ?? [],
+ complete: response.data?.complete ?? false,
+ };
+ },
+ [ruleId, startTime, endTime],
+ );
+
+ return { hardcodedAttributeKeys, valueSuggestionsOverride, isLoadingKeys };
+}
diff --git a/frontend/src/container/AlertHistory/Timeline/Table/useTimelineTable.tsx b/frontend/src/container/AlertHistory/Timeline/Table/useTimelineTable.tsx
index 2b2c88ea0a..ba2c9f9c94 100644
--- a/frontend/src/container/AlertHistory/Timeline/Table/useTimelineTable.tsx
+++ b/frontend/src/container/AlertHistory/Timeline/Table/useTimelineTable.tsx
@@ -1,83 +1,15 @@
-import { useMemo } from 'react';
-import { Ellipsis, Search } from '@signozhq/icons';
-import { Color } from '@signozhq/design-tokens';
-import { Button, TableColumnsType as ColumnsType } from 'antd';
-import ClientSideQBSearch, {
- AttributeKey,
-} from 'components/ClientSideQBSearch/ClientSideQBSearch';
+import { Ellipsis } from '@signozhq/icons';
+import { Button, TableColumnsType as ColumnsType, Tooltip } from 'antd';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import { ConditionalAlertPopover } from 'container/AlertHistory/AlertPopover/AlertPopover';
-import { transformKeyValuesToAttributeValuesMap } from 'container/QueryBuilder/filters/utils';
-import { useIsDarkMode } from 'hooks/useDarkMode';
import { TimestampInput } from 'hooks/useTimezoneFormatter/useTimezoneFormatter';
-import AlertLabels, {
- AlertLabelsProps,
-} from 'pages/AlertDetails/AlertHeader/AlertLabels/AlertLabels';
+import AlertLabels from 'pages/AlertDetails/AlertHeader/AlertLabels/AlertLabels';
import AlertState from 'pages/AlertDetails/AlertHeader/AlertState/AlertState';
import { AlertRuleTimelineTableResponse } from 'types/api/alerts/def';
-import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
-
-const transformLabelsToQbKeys = (
- labels: AlertRuleTimelineTableResponse['labels'],
-): AttributeKey[] => Object.keys(labels).flatMap((key) => [{ key }]);
-
-function LabelFilter({
- filters,
- setFilters,
- labels,
-}: {
- setFilters: (filters: TagFilter) => void;
- filters: TagFilter;
- labels: AlertLabelsProps['labels'];
-}): JSX.Element | null {
- const isDarkMode = useIsDarkMode();
-
- const { transformedKeys, attributesMap } = useMemo(
- () => ({
- transformedKeys: transformLabelsToQbKeys(labels || {}),
- attributesMap: transformKeyValuesToAttributeValuesMap(labels),
- }),
- [labels],
- );
-
- const handleSearch = (tagFilters: TagFilter): void => {
- const tagFiltersLength = tagFilters.items.length;
-
- if (
- (!tagFiltersLength && (!filters || !filters.items.length)) ||
- tagFiltersLength === filters?.items.length
- ) {
- return;
- }
- setFilters(tagFilters);
- };
-
- return (
- <ClientSideQBSearch
- onChange={handleSearch}
- filters={filters}
- className="alert-history-label-search"
- attributeKeys={transformedKeys}
- attributeValuesMap={attributesMap}
- suffixIcon={
- <Search
- size={14}
- color={isDarkMode ? Color.TEXT_VANILLA_100 : Color.TEXT_INK_100}
- />
- }
- />
- );
-}
export const timelineTableColumns = ({
- filters,
- labels,
- setFilters,
formatTimezoneAdjustedTimestamp,
}: {
- filters: TagFilter;
- labels: AlertLabelsProps['labels'];
- setFilters: (filters: TagFilter) => void;
formatTimezoneAdjustedTimestamp: (
input: TimestampInput,
format?: string,
@@ -95,9 +27,7 @@ export const timelineTableColumns = ({
),
},
{
- title: (
- <LabelFilter setFilters={setFilters} filters={filters} labels={labels} />
- ),
+ title: 'LABELS',
dataIndex: 'labels',
render: (labels): JSX.Element => (
<div className="alert-rule-labels">
@@ -119,15 +49,27 @@ export const timelineTableColumns = ({
title: 'ACTIONS',
width: 140,
align: 'right',
- render: (record): JSX.Element => (
- <ConditionalAlertPopover
- relatedTracesLink={record.relatedTracesLink}
- relatedLogsLink={record.relatedLogsLink}
- >
- <Button type="text" ghost>
- <Ellipsis className="dropdown-icon" size="md" />
- </Button>
- </ConditionalAlertPopover>
- ),
+ render: (_, record): JSX.Element => {
+ if (!record.relatedTracesLink && !record.relatedLogsLink) {
+ return (
+ <Tooltip title="No links available for this item">
+ <Button type="text" ghost disabled>
+ <Ellipsis className="dropdown-icon" size="md" />
+ </Button>
+ </Tooltip>
+ );
+ }
+
+ return (
+ <ConditionalAlertPopover
+ relatedTracesLink={record.relatedTracesLink ?? ''}
+ relatedLogsLink={record.relatedLogsLink ?? ''}
+ >
+ <Button type="text" ghost>
+ <Ellipsis className="dropdown-icon" size="md" />
+ </Button>
+ </ConditionalAlertPopover>
+ );
+ },
},
];
diff --git a/frontend/src/container/AlertHistory/Timeline/Table/useTimelineTableCursor.ts b/frontend/src/container/AlertHistory/Timeline/Table/useTimelineTableCursor.ts
new file mode 100644
index 0000000000..22c6c22108
--- /dev/null
+++ b/frontend/src/container/AlertHistory/Timeline/Table/useTimelineTableCursor.ts
@@ -0,0 +1,53 @@
+import {
+ Options,
+ parseAsInteger,
+ parseAsStringLiteral,
+ useQueryState,
+ UseQueryStateReturn,
+} from 'nuqs';
+import { TIMELINE_TABLE_PAGE_SIZE } from 'container/AlertHistory/constants';
+
+const defaultNuqsOptions: Options = {
+ history: 'push',
+};
+
+export const TIMELINE_TABLE_PARAMS = {
+ PAGE: 'page',
+ ORDER: 'order',
+} as const;
+
+const ORDER_VALUES = ['asc', 'desc'] as const;
+export type OrderDirection = (typeof ORDER_VALUES)[number];
+
+export const useTimelineTablePage = (): UseQueryStateReturn<number, number> =>
+ useQueryState(
+ TIMELINE_TABLE_PARAMS.PAGE,
+ parseAsInteger.withDefault(1).withOptions(defaultNuqsOptions),
+ );
+
+export const useTimelineTableOrder = (): UseQueryStateReturn<
+ OrderDirection,
+ OrderDirection
+> =>
+ useQueryState(
+ TIMELINE_TABLE_PARAMS.ORDER,
+ parseAsStringLiteral(ORDER_VALUES)
+ .withDefault('asc')
+ .withOptions(defaultNuqsOptions),
+ );
+
+export function encodeCursor(page: number, limit: number): string | undefined {
+ if (page <= 1) {
+ return undefined;
+ }
+ const offset = (page - 1) * limit;
+ // Backend uses base64.RawURLEncoding (URL-safe, no padding)
+ return btoa(JSON.stringify({ offset, limit }))
+ .replace(/\+/g, '-')
+ .replace(/\//g, '_')
+ .replace(/=+$/, '');
+}
+
+export function computeCursorForPage(page: number): string | undefined {
+ return encodeCursor(page, TIMELINE_TABLE_PAGE_SIZE);
+}
diff --git a/frontend/src/container/AlertHistory/Timeline/Table/utils.ts b/frontend/src/container/AlertHistory/Timeline/Table/utils.ts
new file mode 100644
index 0000000000..1ac9fd33a2
--- /dev/null
+++ b/frontend/src/container/AlertHistory/Timeline/Table/utils.ts
@@ -0,0 +1,26 @@
+import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
+import { QueryKeyDataSuggestionsProps } from 'types/api/querySuggestions/types';
+
+const fieldContextToSuggestionMap: Record<
+ TelemetrytypesFieldContextDTO,
+ QueryKeyDataSuggestionsProps['fieldContext']
+> = {
+ [TelemetrytypesFieldContextDTO.resource]: 'resource',
+ [TelemetrytypesFieldContextDTO.span]: 'span',
+ [TelemetrytypesFieldContextDTO.attribute]: 'attribute',
+ // no maps for the following values on suggestion context
+ [TelemetrytypesFieldContextDTO.body]: undefined,
+ [TelemetrytypesFieldContextDTO.metric]: undefined,
+ [TelemetrytypesFieldContextDTO.log]: undefined,
+ [TelemetrytypesFieldContextDTO['']]: undefined,
+};
+
+export function fieldContextToSuggestionContext(
+ fc: TelemetrytypesFieldContextDTO | undefined,
+): QueryKeyDataSuggestionsProps['fieldContext'] {
+ if (fc === undefined) {
+ return undefined;
+ }
+
+ return fieldContextToSuggestionMap[fc];
+}
diff --git a/frontend/src/container/AlertHistory/utils/labelAdapters.ts b/frontend/src/container/AlertHistory/utils/labelAdapters.ts
new file mode 100644
index 0000000000..fa94b3f7ac
--- /dev/null
+++ b/frontend/src/container/AlertHistory/utils/labelAdapters.ts
@@ -0,0 +1,19 @@
+import type { Querybuildertypesv5LabelDTO } from 'api/generated/services/sigNoz.schemas';
+import type { Labels } from 'types/api/alerts/def';
+
+export function labelsArrayToObject(
+ labels: Querybuildertypesv5LabelDTO[] | null | undefined,
+): Labels {
+ if (!labels) {
+ return {};
+ }
+
+ return labels.reduce<Labels>((acc, label) => {
+ const key = label.key?.name ?? '';
+ const value = String(label.value ?? '');
+ if (key) {
+ acc[key] = value;
+ }
+ return acc;
+ }, {});
+}
diff --git a/frontend/src/pages/AlertDetails/AlertHeader/AlertState/AlertState.tsx b/frontend/src/pages/AlertDetails/AlertHeader/AlertState/AlertState.tsx
index 05ea7e698b..a23ce1dba5 100644
--- a/frontend/src/pages/AlertDetails/AlertHeader/AlertState/AlertState.tsx
+++ b/frontend/src/pages/AlertDetails/AlertHeader/AlertState/AlertState.tsx
@@ -1,11 +1,12 @@
import { Color } from '@signozhq/design-tokens';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { BellOff, CircleCheck, CircleOff, Flame } from '@signozhq/icons';
+import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
import './AlertState.styles.scss';
type AlertStateProps = {
- state: string;
+ state: RuletypesAlertStateDTO | string;
showLabel?: boolean;
};
@@ -17,7 +18,7 @@ export default function AlertState({
let label;
const isDarkMode = useIsDarkMode();
switch (state) {
- case 'nodata':
+ case RuletypesAlertStateDTO.nodata:
icon = (
<CircleOff
size={18}
@@ -28,7 +29,7 @@ export default function AlertState({
label = <span style={{ color: Color.BG_SIENNA_400 }}>No Data</span>;
break;
- case 'disabled':
+ case RuletypesAlertStateDTO.disabled:
icon = (
<BellOff
size={18}
@@ -38,15 +39,16 @@ export default function AlertState({
);
label = <span style={{ color: Color.BG_VANILLA_400 }}>Muted</span>;
break;
- case 'firing':
+
+ case RuletypesAlertStateDTO.firing:
icon = (
<Flame size={18} fill={Color.BG_CHERRY_500} color={Color.BG_CHERRY_500} />
);
label = <span style={{ color: Color.BG_CHERRY_500 }}>Firing</span>;
break;
- case 'normal':
- case 'inactive':
+ case RuletypesAlertStateDTO.inactive:
+ case 'normal': // legacy
icon = (
<CircleCheck
size={18}
diff --git a/frontend/src/pages/AlertDetails/hooks.tsx b/frontend/src/pages/AlertDetails/hooks.tsx
index 31117bc2b4..402c5b3ff5 100644
--- a/frontend/src/pages/AlertDetails/hooks.tsx
+++ b/frontend/src/pages/AlertDetails/hooks.tsx
@@ -1,28 +1,34 @@
-import { useCallback, useMemo } from 'react';
-import { useMutation, useQuery, useQueryClient } from 'react-query';
-import { generatePath, useLocation } from 'react-router-dom';
+import { useCallback, useEffect, useMemo, useRef } from 'react';
+import { useMutation, useQueryClient, useQuery } from 'react-query';
+import { generatePath } from 'react-router-dom';
import { TablePaginationConfig, TableProps } from 'antd';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import { patchRulePartial } from 'api/alerts/patchRulePartial';
-import ruleStats from 'api/alerts/ruleStats';
-import timelineGraph from 'api/alerts/timelineGraph';
-import timelineTable from 'api/alerts/timelineTable';
-import topContributors from 'api/alerts/topContributors';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import {
createRule,
deleteRuleByID,
getGetRuleByIDQueryKey,
+ getGetRuleHistoryTimelineQueryOptions,
invalidateGetRuleByID,
invalidateListRules,
updateRuleByID,
useGetRuleByID,
+ useGetRuleHistoryOverallStatus,
+ useGetRuleHistoryStats,
+ useGetRuleHistoryTopContributors,
useListRules,
} from 'api/generated/services/rules';
-import type {
- GetRuleByID200,
- RenderErrorResponseDTO,
- RuletypesPostableRuleDTO,
+import {
+ Querybuildertypesv5OrderDirectionDTO,
+ RuletypesAlertStateDTO,
+ type GetRuleByID200,
+ type GetRuleHistoryOverallStatus200,
+ type GetRuleHistoryStats200,
+ type GetRuleHistoryTimeline200,
+ type GetRuleHistoryTopContributors200,
+ type RenderErrorResponseDTO,
+ type RuletypesPostableRuleDTO,
} from 'api/generated/services/sigNoz.schemas';
import { AxiosError } from 'axios';
import { TabRoutes } from 'components/RouteTab/types';
@@ -31,35 +37,27 @@ import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import ROUTES from 'constants/routes';
import AlertHistory from 'container/AlertHistory';
import { TIMELINE_TABLE_PAGE_SIZE } from 'container/AlertHistory/constants';
+import {
+ computeCursorForPage,
+ useTimelineTableOrder,
+ useTimelineTablePage,
+} from 'container/AlertHistory/Timeline/Table/useTimelineTableCursor';
import { AlertDetailsTab, TimelineFilter } from 'container/AlertHistory/types';
-import { urlKey } from 'container/AllError/utils';
import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constants';
import { useNotifications } from 'hooks/useNotifications';
-import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
-import createQueryParams from 'lib/createQueryParams';
import GetMinMax from 'lib/getMinMax';
import history from 'lib/history';
import { History, Table } from '@signozhq/icons';
import EditRules from 'pages/EditRules';
-import { OrderPreferenceItems } from 'pages/Logs/config';
import BetaTag from 'periscope/components/BetaTag/BetaTag';
-import PaginationInfoText from 'periscope/components/PaginationInfoText/PaginationInfoText';
import { useAlertRule } from 'providers/Alert';
import { useErrorModal } from 'providers/ErrorModalProvider';
-import { ErrorResponse, SuccessResponse } from 'types/api';
import { toPostableRuleDTOFromAlertDef } from 'types/api/alerts/convert';
-import {
- AlertDef,
- AlertRuleStatsPayload,
- AlertRuleTimelineGraphResponsePayload,
- AlertRuleTimelineTableResponse,
- AlertRuleTimelineTableResponsePayload,
- AlertRuleTopContributorsPayload,
-} from 'types/api/alerts/def';
+import { AlertDef, AlertRuleTimelineTableResponse } from 'types/api/alerts/def';
import APIError from 'types/api/error';
-import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { nanoToMilli } from 'utils/timeUtils';
+import { Typography } from '@signozhq/ui/typography';
export const useAlertHistoryQueryParams = (): {
ruleId: string | null;
@@ -201,10 +199,7 @@ type GetAlertRuleDetailsApiProps = {
};
type GetAlertRuleDetailsStatsProps = GetAlertRuleDetailsApiProps & {
- data:
- | SuccessResponse<AlertRuleStatsPayload, unknown>
- | ErrorResponse
- | undefined;
+ data: GetRuleHistoryStats200 | undefined;
};
export const useGetAlertRuleDetailsStats =
@@ -213,18 +208,15 @@ export const useGetAlertRuleDetailsStats =
const isValidRuleId = ruleId !== null && String(ruleId).length !== 0;
- const { isLoading, isRefetching, isError, data } = useQuery(
- [REACT_QUERY_KEY.ALERT_RULE_STATS, ruleId, startTime, endTime],
+ const { isLoading, isRefetching, isError, data } = useGetRuleHistoryStats(
+ { id: ruleId || '' },
+ { start: startTime, end: endTime },
{
- queryFn: () =>
- ruleStats({
- id: ruleId || '',
- start: startTime,
- end: endTime,
- }),
- enabled: isValidRuleId && !!startTime && !!endTime,
- refetchOnMount: false,
- refetchOnWindowFocus: false,
+ query: {
+ enabled: isValidRuleId && !!startTime && !!endTime,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ },
},
);
@@ -232,10 +224,7 @@ export const useGetAlertRuleDetailsStats =
};
type GetAlertRuleDetailsTopContributorsProps = GetAlertRuleDetailsApiProps & {
- data:
- | SuccessResponse<AlertRuleTopContributorsPayload, unknown>
- | ErrorResponse
- | undefined;
+ data: GetRuleHistoryTopContributors200 | undefined;
};
export const useGetAlertRuleDetailsTopContributors =
@@ -244,90 +233,128 @@ export const useGetAlertRuleDetailsTopContributors =
const isValidRuleId = ruleId !== null && String(ruleId).length !== 0;
- const { isLoading, isRefetching, isError, data } = useQuery(
- [REACT_QUERY_KEY.ALERT_RULE_TOP_CONTRIBUTORS, ruleId, startTime, endTime],
- {
- queryFn: () =>
- topContributors({
- id: ruleId || '',
- start: startTime,
- end: endTime,
- }),
- enabled: isValidRuleId,
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- },
- );
+ const { isLoading, isRefetching, isError, data } =
+ useGetRuleHistoryTopContributors(
+ { id: ruleId || '' },
+ { start: startTime, end: endTime },
+ {
+ query: {
+ enabled: isValidRuleId && !!startTime && !!endTime,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ },
+ },
+ );
return { isLoading, isRefetching, isError, data, isValidRuleId, ruleId };
};
type GetAlertRuleDetailsTimelineTableProps = GetAlertRuleDetailsApiProps & {
- data:
- | SuccessResponse<AlertRuleTimelineTableResponsePayload, unknown>
- | ErrorResponse
- | undefined;
+ data: GetRuleHistoryTimeline200 | undefined;
+ error: AxiosError<RenderErrorResponseDTO> | null;
+ refetch: () => void;
+ cancel: () => void;
};
export const useGetAlertRuleDetailsTimelineTable = ({
- filters,
+ filterExpression,
}: {
- filters: TagFilter;
+ filterExpression: string;
}): GetAlertRuleDetailsTimelineTableProps => {
+ const queryClient = useQueryClient();
const { ruleId, startTime, endTime, params } = useAlertHistoryQueryParams();
- const { updatedOrder, offset } = useMemo(
- () => ({
- updatedOrder: params.get(urlKey.order) ?? OrderPreferenceItems.ASC,
- offset: parseInt(params.get(urlKey.offset) ?? '0', 10),
- }),
- [params],
+ const [page, setPage] = useTimelineTablePage();
+ const [order] = useTimelineTableOrder();
+
+ const updatedOrder = useMemo(
+ () =>
+ order === 'asc'
+ ? Querybuildertypesv5OrderDirectionDTO.asc
+ : Querybuildertypesv5OrderDirectionDTO.desc,
+ [order],
);
const timelineFilter = params.get('timelineFilter');
const isValidRuleId = ruleId !== null && String(ruleId).length !== 0;
- const hasStartAndEnd = startTime !== null && endTime !== null;
-
- const { isLoading, isRefetching, isError, data } = useQuery(
- [
- REACT_QUERY_KEY.ALERT_RULE_TIMELINE_TABLE,
- ruleId,
- startTime,
- endTime,
- timelineFilter,
- updatedOrder,
- offset,
- JSON.stringify(filters.items),
- ],
+
+ const stateFilter = useMemo(() => {
+ if (!timelineFilter || timelineFilter === TimelineFilter.ALL) {
+ return undefined;
+ }
+ return timelineFilter === TimelineFilter.FIRED
+ ? RuletypesAlertStateDTO.firing
+ : RuletypesAlertStateDTO.inactive;
+ }, [timelineFilter]);
+
+ const filtersKey = `${filterExpression}|${stateFilter ?? ''}|${startTime}|${endTime}`;
+ const prevFiltersKeyRef = useRef(filtersKey);
+ const filtersChanged = prevFiltersKeyRef.current !== filtersKey;
+ const cursor = computeCursorForPage(filtersChanged ? 1 : page);
+
+ useEffect(() => {
+ if (prevFiltersKeyRef.current !== filtersKey) {
+ prevFiltersKeyRef.current = filtersKey;
+ if (page > 1) {
+ void setPage(1);
+ }
+ }
+ }, [filtersKey, page, setPage]);
+
+ const queryParams = useMemo(
+ () => ({
+ start: startTime,
+ end: endTime,
+ limit: TIMELINE_TABLE_PAGE_SIZE,
+ order: updatedOrder,
+ cursor,
+ filterExpression: filterExpression || undefined,
+ state: stateFilter,
+ }),
+ [startTime, endTime, updatedOrder, cursor, filterExpression, stateFilter],
+ );
+
+ const queryOptions = getGetRuleHistoryTimelineQueryOptions(
+ { id: ruleId || '' },
+ queryParams,
{
- queryFn: () =>
- timelineTable({
- id: ruleId || '',
- start: startTime,
- end: endTime,
- limit: TIMELINE_TABLE_PAGE_SIZE,
- order: updatedOrder,
- offset,
- filters,
- ...(timelineFilter && timelineFilter !== TimelineFilter.ALL
- ? {
- state: timelineFilter === TimelineFilter.FIRED ? 'firing' : 'normal',
- }
- : {}),
- }),
- enabled: isValidRuleId && hasStartAndEnd,
- refetchOnMount: false,
- refetchOnWindowFocus: false,
+ query: {
+ enabled: isValidRuleId,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ },
},
);
- return { isLoading, isRefetching, isError, data, isValidRuleId, ruleId };
+ const { isLoading, isRefetching, isError, data, error, refetch } =
+ useQuery(queryOptions);
+
+ const queryKeyRef = useRef(queryOptions.queryKey);
+ queryKeyRef.current = queryOptions.queryKey;
+
+ const cancel = useCallback(() => {
+ void queryClient.cancelQueries({ queryKey: queryKeyRef.current });
+ }, [queryClient]);
+
+ return {
+ isLoading,
+ isRefetching,
+ isError,
+ data,
+ error: error as AxiosError<RenderErrorResponseDTO> | null,
+ isValidRuleId,
+ ruleId,
+ refetch,
+ cancel,
+ };
};
export const useTimelineTable = ({
totalItems,
+ nextCursor,
}: {
totalItems: number;
+ nextCursor?: string;
}): {
paginationConfig: TablePaginationConfig;
onChangeHandler: (
@@ -336,16 +363,13 @@ export const useTimelineTable = ({
filters: any,
extra: any,
) => void;
+ handleNextPage: () => void;
+ handlePrevPage: () => void;
+ hasNextPage: boolean;
+ hasPrevPage: boolean;
} => {
- const { safeNavigate } = useSafeNavigate();
-
- const { pathname } = useLocation();
-
- const { search } = useLocation();
-
- const params = useMemo(() => new URLSearchParams(search), [search]);
-
- const offset = params.get('offset') ?? '0';
+ const [page, setPage] = useTimelineTablePage();
+ const [, setOrder] = useTimelineTableOrder();
const onChangeHandler: TableProps<AlertRuleTimelineTableResponse>['onChange'] =
useCallback(
@@ -357,38 +381,52 @@ export const useTimelineTable = ({
| SorterResult<AlertRuleTimelineTableResponse>,
) => {
if (!Array.isArray(sorter)) {
- const { pageSize = 0, current = 0 } = pagination;
const { order } = sorter;
const updatedOrder = order === 'ascend' ? 'asc' : 'desc';
- const params = new URLSearchParams(window.location.search);
-
- safeNavigate(
- `${pathname}?${createQueryParams({
- ...Object.fromEntries(params),
- order: updatedOrder,
- offset: current * TIMELINE_TABLE_PAGE_SIZE - TIMELINE_TABLE_PAGE_SIZE,
- pageSize,
- })}`,
- );
+ void Promise.all([setOrder(updatedOrder), setPage(1)]);
}
},
- [pathname, safeNavigate],
+ [setOrder, setPage],
);
- const offsetInt = parseInt(offset, 10);
- const pageSize = params.get('pageSize') ?? String(TIMELINE_TABLE_PAGE_SIZE);
- const pageSizeInt = parseInt(pageSize, 10);
+ const handleNextPage = useCallback(() => {
+ if (!nextCursor) {
+ return;
+ }
+ void setPage(page + 1);
+ }, [nextCursor, page, setPage]);
+
+ const handlePrevPage = useCallback(() => {
+ if (page <= 1) {
+ return;
+ }
+ void setPage(page - 1);
+ }, [page, setPage]);
const paginationConfig: TablePaginationConfig = {
- pageSize: pageSizeInt,
- showTotal: PaginationInfoText,
- current: offsetInt / TIMELINE_TABLE_PAGE_SIZE + 1,
+ pageSize: TIMELINE_TABLE_PAGE_SIZE,
+ showTotal: (total, [start, end]) => (
+ <span>
+ <Typography.Text size="small">
+ {start} &#8212; {end}
+ </Typography.Text>
+ <Typography.Text size="small"> of {total}</Typography.Text>
+ </span>
+ ),
+ current: page,
showSizeChanger: false,
hideOnSinglePage: true,
total: totalItems,
};
- return { paginationConfig, onChangeHandler };
+ return {
+ paginationConfig,
+ onChangeHandler,
+ handleNextPage,
+ handlePrevPage,
+ hasNextPage: !!nextCursor,
+ hasPrevPage: page > 1,
+ };
};
export const useAlertRuleStatusToggle = ({
@@ -581,10 +619,7 @@ export const useAlertRuleDelete = ({
};
type GetAlertRuleDetailsTimelineGraphProps = GetAlertRuleDetailsApiProps & {
- data:
- | SuccessResponse<AlertRuleTimelineGraphResponsePayload, unknown>
- | ErrorResponse
- | undefined;
+ data: GetRuleHistoryOverallStatus200 | undefined;
};
export const useGetAlertRuleDetailsTimelineGraphData =
@@ -594,20 +629,18 @@ export const useGetAlertRuleDetailsTimelineGraphData =
const isValidRuleId = ruleId !== null && String(ruleId).length !== 0;
const hasStartAndEnd = startTime !== null && endTime !== null;
- const { isLoading, isRefetching, isError, data } = useQuery(
- [REACT_QUERY_KEY.ALERT_RULE_TIMELINE_GRAPH, ruleId, startTime, endTime],
- {
- queryFn: () =>
- timelineGraph({
- id: ruleId || '',
- start: startTime,
- end: endTime,
- }),
- enabled: isValidRuleId && hasStartAndEnd,
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- },
- );
+ const { isLoading, isRefetching, isError, data } =
+ useGetRuleHistoryOverallStatus(
+ { id: ruleId || '' },
+ { start: startTime, end: endTime },
+ {
+ query: {
+ enabled: isValidRuleId && hasStartAndEnd,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ },
+ },
+ );
return { isLoading, isRefetching, isError, data, isValidRuleId, ruleId };
};
diff --git a/frontend/src/types/api/alerts/def.ts b/frontend/src/types/api/alerts/def.ts
index 6a977e23cc..af82f4d956 100644
--- a/frontend/src/types/api/alerts/def.ts
+++ b/frontend/src/types/api/alerts/def.ts
@@ -1,4 +1,4 @@
-import { AlertLabelsProps } from 'pages/AlertDetails/AlertHeader/AlertLabels/AlertLabels';
+import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
import { ICompositeMetricQuery } from 'types/api/alerts/compositeQuery';
// default match type for threshold
@@ -73,10 +73,6 @@ export interface StatsTimeSeriesItem {
value: string;
}
-export type AlertRuleStatsPayload = {
- data: AlertRuleStats;
-};
-
export interface AlertRuleTopContributors {
fingerprint: number;
labels: Labels;
@@ -84,9 +80,6 @@ export interface AlertRuleTopContributors {
relatedLogsLink: string;
relatedTracesLink: string;
}
-export type AlertRuleTopContributorsPayload = {
- data: AlertRuleTopContributors[];
-};
export interface AlertRuleTimelineTableResponse {
ruleID: string;
@@ -99,24 +92,12 @@ export interface AlertRuleTimelineTableResponse {
labels: Labels;
fingerprint: number;
value: number;
- relatedTracesLink: string;
- relatedLogsLink: string;
+ relatedLogsLink?: string;
+ relatedTracesLink?: string;
}
-export type AlertRuleTimelineTableResponsePayload = {
- data: {
- items: AlertRuleTimelineTableResponse[];
- total: number;
- labels: AlertLabelsProps['labels'];
- };
-};
-
-type AlertState = 'firing' | 'normal' | 'nodata' | 'muted';
export interface AlertRuleTimelineGraphResponse {
start: number;
end: number;
- state: AlertState;
+ state: RuletypesAlertStateDTO;
}
-export type AlertRuleTimelineGraphResponsePayload = {
- data: AlertRuleTimelineGraphResponse[];
-};
diff --git a/frontend/src/types/api/alerts/ruleStats.ts b/frontend/src/types/api/alerts/ruleStats.ts
deleted file mode 100644
index 2669a4c6be..0000000000
--- a/frontend/src/types/api/alerts/ruleStats.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { AlertDef } from './def';
-
-export interface RuleStatsProps {
- id: AlertDef['id'];
- start: number;
- end: number;
-}
diff --git a/frontend/src/types/api/alerts/timelineGraph.ts b/frontend/src/types/api/alerts/timelineGraph.ts
deleted file mode 100644
index 99e9601f1e..0000000000
--- a/frontend/src/types/api/alerts/timelineGraph.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { AlertDef } from './def';
-
-export interface GetTimelineGraphRequestProps {
- id: AlertDef['id'];
- start: number;
- end: number;
-}
diff --git a/frontend/src/types/api/alerts/timelineTable.ts b/frontend/src/types/api/alerts/timelineTable.ts
deleted file mode 100644
index b2e27a4d1c..0000000000
--- a/frontend/src/types/api/alerts/timelineTable.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { TagFilter } from '../queryBuilder/queryBuilderData';
-import { AlertDef } from './def';
-
-export interface GetTimelineTableRequestProps {
- id: AlertDef['id'];
- start: number;
- end: number;
- offset: number;
- limit: number;
- order: string;
- filters?: TagFilter;
- state?: string;
-}
diff --git a/frontend/src/types/api/alerts/topContributors.ts b/frontend/src/types/api/alerts/topContributors.ts
deleted file mode 100644
index 74acb4b871..0000000000
--- a/frontend/src/types/api/alerts/topContributors.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { AlertDef } from './def';
-
-export interface TopContributorsProps {
- id: AlertDef['id'];
- start: number;
- end: number;
-}
diff --git a/pkg/modules/rulestatehistory/implrulestatehistory/store.go b/pkg/modules/rulestatehistory/implrulestatehistory/store.go
index a411b527c2..95beb61593 100644
--- a/pkg/modules/rulestatehistory/implrulestatehistory/store.go
+++ b/pkg/modules/rulestatehistory/implrulestatehistory/store.go
@@ -485,9 +485,11 @@ func (s *store) buildFilterClause(ctx context.Context, orgID valuer.UUID, filter
}
fieldKeys, _, err := s.telemetryMetadataStore.GetKeysMulti(ctx, orgID, selectors)
- if err != nil || len(fieldKeys) == 0 {
+ if err != nil || fieldKeys == nil {
fieldKeys = map[string][]*telemetrytypes.TelemetryFieldKey{}
- for _, sel := range selectors {
+ }
+ for _, sel := range selectors {
+ if len(fieldKeys[sel.Name]) == 0 {
fieldKeys[sel.Name] = []*telemetrytypes.TelemetryFieldKey{{
Name: sel.Name,
Signal: sel.Signal,