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.

refactor: update logs explorer pagination logic (#7010)

Shaheer Kochai16140991be50
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index c16339d517..4f215d82e9 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -15,6 +15,7 @@ const config: Config.InitialOptions = {
extensionsToTreatAsEsm: ['.ts'],
'ts-jest': {
useESM: true,
+ isolatedModules: true,
},
},
testMatch: ['<rootDir>/src/**/*?(*.)(test).(ts|js)?(x)'],
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricLogsDetailedView.tsx b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricLogsDetailedView.tsx
index ec88ef49e6..611295f8f3 100644
--- a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricLogsDetailedView.tsx
+++ b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricLogsDetailedView.tsx
@@ -87,11 +87,7 @@ function HostMetricLogsDetailedView({
/>
</div>
</div>
- <HostMetricsLogs
- timeRange={timeRange}
- handleChangeLogFilters={handleChangeLogFilters}
- filters={logFilters}
- />
+ <HostMetricsLogs timeRange={timeRange} filters={logFilters} />
</div>
);
}
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricsLogs.tsx b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricsLogs.tsx
index bb5c17a506..8279336eea 100644
--- a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricsLogs.tsx
+++ b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/HostMetricsLogs.tsx
@@ -8,19 +8,13 @@ import { DEFAULT_ENTITY_VERSION } from 'constants/app';
import LogsError from 'container/LogsError/LogsError';
import { LogsLoading } from 'container/LogsLoading/LogsLoading';
import { FontSize } from 'container/OptionsMenu/types';
-import { ORDERBY_FILTERS } from 'container/QueryBuilder/filters/OrderByFilter/config';
+import { useHandleLogsPagination } from 'hooks/infraMonitoring/useHandleLogsPagination';
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
-import { isEqual } from 'lodash-es';
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo } from 'react';
import { useQuery } from 'react-query';
import { Virtuoso } from 'react-virtuoso';
import { ILog } from 'types/api/logs/log';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- TagFilterItem,
-} from 'types/api/queryBuilder/queryBuilderData';
-import { v4 } from 'uuid';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { getHostLogsQueryPayload } from './constants';
import NoLogsContainer from './NoLogsContainer';
@@ -30,51 +24,30 @@ interface Props {
startTime: number;
endTime: number;
};
- handleChangeLogFilters: (filters: IBuilderQuery['filters']) => void;
filters: IBuilderQuery['filters'];
}
-function HostMetricsLogs({
- timeRange,
- handleChangeLogFilters,
- filters,
-}: Props): JSX.Element {
- const [logs, setLogs] = useState<ILog[]>([]);
- const [hasReachedEndOfLogs, setHasReachedEndOfLogs] = useState(false);
- const [restFilters, setRestFilters] = useState<TagFilterItem[]>([]);
- const [resetLogsList, setResetLogsList] = useState<boolean>(false);
-
- useEffect(() => {
- const newRestFilters = filters.items.filter(
- (item) => item.key?.key !== 'id' && item.key?.key !== 'host.name',
- );
-
- const areFiltersSame = isEqual(restFilters, newRestFilters);
-
- if (!areFiltersSame) {
- setResetLogsList(true);
- }
-
- setRestFilters(newRestFilters);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [filters]);
-
- const queryPayload = useMemo(() => {
- const basePayload = getHostLogsQueryPayload(
- timeRange.startTime,
- timeRange.endTime,
- filters,
- );
-
- basePayload.query.builder.queryData[0].pageSize = 100;
- basePayload.query.builder.queryData[0].orderBy = [
- { columnName: 'timestamp', order: ORDERBY_FILTERS.DESC },
- ];
-
- return basePayload;
- }, [timeRange.startTime, timeRange.endTime, filters]);
-
- const [isPaginating, setIsPaginating] = useState(false);
+function HostMetricsLogs({ timeRange, filters }: Props): JSX.Element {
+ const basePayload = getHostLogsQueryPayload(
+ timeRange.startTime,
+ timeRange.endTime,
+ filters,
+ );
+ const {
+ logs,
+ hasReachedEndOfLogs,
+ isPaginating,
+ currentPage,
+ setIsPaginating,
+ handleNewData,
+ loadMoreLogs,
+ queryPayload,
+ } = useHandleLogsPagination({
+ timeRange,
+ filters,
+ excludeFilterKeys: ['host.name'],
+ basePayload,
+ });
const { data, isLoading, isFetching, isError } = useQuery({
queryKey: [
@@ -82,6 +55,7 @@ function HostMetricsLogs({
timeRange.startTime,
timeRange.endTime,
filters,
+ currentPage,
],
queryFn: () => GetMetricQueryRange(queryPayload, DEFAULT_ENTITY_VERSION),
enabled: !!queryPayload,
@@ -90,33 +64,13 @@ function HostMetricsLogs({
useEffect(() => {
if (data?.payload?.data?.newResult?.data?.result) {
- const currentData = data.payload.data.newResult.data.result;
-
- if (resetLogsList) {
- const currentLogs: ILog[] =
- currentData[0].list?.map((item) => ({
- ...item.data,
- timestamp: item.timestamp,
- })) || [];
-
- setLogs(currentLogs);
-
- setResetLogsList(false);
- }
-
- if (currentData.length > 0 && currentData[0].list) {
- const currentLogs: ILog[] =
- currentData[0].list.map((item) => ({
- ...item.data,
- timestamp: item.timestamp,
- })) || [];
-
- setLogs((prev) => [...prev, ...currentLogs]);
- } else {
- setHasReachedEndOfLogs(true);
- }
+ handleNewData(data.payload.data.newResult.data.result);
}
- }, [data, restFilters, isPaginating, resetLogsList]);
+ }, [data, handleNewData]);
+
+ useEffect(() => {
+ setIsPaginating(false);
+ }, [data, setIsPaginating]);
const getItemContent = useCallback(
(_: number, logToRender: ILog): JSX.Element => (
@@ -144,39 +98,6 @@ function HostMetricsLogs({
[],
);
- const loadMoreLogs = useCallback(() => {
- if (!logs.length) return;
-
- setIsPaginating(true);
- const lastLog = logs[logs.length - 1];
-
- const newItems = [
- ...filters.items.filter((item) => item.key?.key !== 'id'),
- {
- id: v4(),
- key: {
- key: 'id',
- type: '',
- dataType: DataTypes.String,
- isColumn: true,
- },
- op: '<',
- value: lastLog.id,
- },
- ];
-
- const newFilters = {
- op: 'AND',
- items: newItems,
- } as IBuilderQuery['filters'];
-
- handleChangeLogFilters(newFilters);
- }, [logs, filters, handleChangeLogFilters]);
-
- useEffect(() => {
- setIsPaginating(false);
- }, [data]);
-
const renderFooter = useCallback(
(): JSX.Element | null => (
// eslint-disable-next-line react/jsx-no-useless-fragment
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/__tests__/HostMetricsLogs.test.tsx b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/__tests__/HostMetricsLogs.test.tsx
new file mode 100644
index 0000000000..fd6bf39583
--- /dev/null
+++ b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/__tests__/HostMetricsLogs.test.tsx
@@ -0,0 +1,168 @@
+import { ENVIRONMENT } from 'constants/env';
+import {
+ verifyFiltersAndOrderBy,
+ verifyPayload,
+} from 'container/LogsExplorerViews/tests/LogsExplorerPagination.test';
+import { logsPaginationQueryRangeSuccessResponse } from 'mocks-server/__mockdata__/logs_query_range';
+import { server } from 'mocks-server/server';
+import { rest } from 'msw';
+import { VirtuosoMockContext } from 'react-virtuoso';
+import {
+ act,
+ fireEvent,
+ render,
+ RenderResult,
+ waitFor,
+} from 'tests/test-utils';
+import { QueryRangePayload } from 'types/api/metrics/getQueryRange';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+
+import HostMetricsLogs from '../HostMetricsLogs';
+
+jest.mock('uplot', () => {
+ const paths = {
+ spline: jest.fn(),
+ bars: jest.fn(),
+ };
+ const uplotMock = jest.fn(() => ({
+ paths,
+ }));
+ return {
+ paths,
+ default: uplotMock,
+ };
+});
+
+jest.mock(
+ 'components/OverlayScrollbar/OverlayScrollbar',
+ () =>
+ function MockOverlayScrollbar({
+ children,
+ }: {
+ children: React.ReactNode;
+ }): JSX.Element {
+ return <div>{children}</div>;
+ },
+);
+
+describe('HostMetricsLogs', () => {
+ let capturedQueryRangePayloads: QueryRangePayload[] = [];
+ const itemHeight = 100;
+ beforeEach(() => {
+ server.use(
+ rest.post(
+ `${ENVIRONMENT.baseURL}/api/v3/query_range`,
+ async (req, res, ctx) => {
+ capturedQueryRangePayloads.push(await req.json());
+
+ const lastPayload =
+ capturedQueryRangePayloads[capturedQueryRangePayloads.length - 1];
+
+ const queryData = lastPayload?.compositeQuery.builderQueries
+ ?.A as IBuilderQuery;
+
+ const offset = queryData?.offset ?? 0;
+
+ return res(
+ ctx.status(200),
+ ctx.json(logsPaginationQueryRangeSuccessResponse({ offset })),
+ );
+ },
+ ),
+ );
+ capturedQueryRangePayloads = [];
+ });
+ it('should check if host logs pagination flows work properly', async () => {
+ let renderResult: RenderResult;
+ let scrollableElement: HTMLElement;
+
+ await act(async () => {
+ renderResult = render(
+ <VirtuosoMockContext.Provider value={{ viewportHeight: 500, itemHeight }}>
+ <HostMetricsLogs
+ timeRange={{ startTime: 0, endTime: 0 }}
+ filters={{ items: [], op: 'AND' }}
+ />
+ </VirtuosoMockContext.Provider>,
+ );
+ });
+
+ await waitFor(() => {
+ expect(capturedQueryRangePayloads.length).toBe(1);
+ });
+
+ await waitFor(async () => {
+ // Find the Virtuoso scroller element by its data-test-id
+ scrollableElement = renderResult.container.querySelector(
+ '[data-test-id="virtuoso-scroller"]',
+ ) as HTMLElement;
+
+ // Ensure the element exists
+ expect(scrollableElement).not.toBeNull();
+
+ if (scrollableElement) {
+ // Set the scrollTop property to simulate scrolling to the calculated end position
+ scrollableElement.scrollTop = 99 * itemHeight;
+
+ act(() => {
+ fireEvent.scroll(scrollableElement);
+ });
+ }
+ });
+
+ await waitFor(() => {
+ expect(capturedQueryRangePayloads.length).toBe(2);
+ });
+
+ const firstPayload = capturedQueryRangePayloads[0];
+ verifyPayload({
+ payload: firstPayload,
+ expectedOffset: 0,
+ });
+
+ // Store the time range from the first payload, which should be consistent in subsequent requests
+ const initialTimeRange = {
+ start: firstPayload.start,
+ end: firstPayload.end,
+ };
+
+ const secondPayload = capturedQueryRangePayloads[1];
+ const secondQueryData = verifyPayload({
+ payload: secondPayload,
+ expectedOffset: 100,
+ initialTimeRange,
+ });
+ verifyFiltersAndOrderBy(secondQueryData);
+
+ await waitFor(async () => {
+ // Find the Virtuoso scroller element by its data-test-id
+ scrollableElement = renderResult.container.querySelector(
+ '[data-test-id="virtuoso-scroller"]',
+ ) as HTMLElement;
+
+ // Ensure the element exists
+ expect(scrollableElement).not.toBeNull();
+
+ if (scrollableElement) {
+ // Set the scrollTop property to simulate scrolling to the calculated end position
+ scrollableElement.scrollTop = 199 * itemHeight;
+
+ act(() => {
+ fireEvent.scroll(scrollableElement);
+ });
+ }
+ });
+
+ await waitFor(() => {
+ expect(capturedQueryRangePayloads.length).toBeGreaterThanOrEqual(3);
+ });
+
+ const thirdPayload = capturedQueryRangePayloads[2];
+ const thirdQueryData = verifyPayload({
+ payload: thirdPayload,
+ expectedOffset: 200,
+ initialTimeRange,
+ });
+ verifyFiltersAndOrderBy(thirdQueryData);
+ });
+});
diff --git a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/constants.ts b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/constants.ts
index eec48b9c39..4acbcb567b 100644
--- a/frontend/src/components/HostMetricsDetail/HostMetricsLogs/constants.ts
+++ b/frontend/src/components/HostMetricsDetail/HostMetricsLogs/constants.ts
@@ -57,9 +57,6 @@ export const getHostLogsQueryPayload = (
id: uuidv4(),
queryType: EQueryType.QUERY_BUILDER,
},
- params: {
- lastLogLineTimestamp: null,
- },
start,
end,
});
diff --git a/frontend/src/container/GridCardLayout/GridCard/index.tsx b/frontend/src/container/GridCardLayout/GridCard/index.tsx
index 7a968c7edf..c29050ca6b 100644
--- a/frontend/src/container/GridCardLayout/GridCard/index.tsx
+++ b/frontend/src/container/GridCardLayout/GridCard/index.tsx
@@ -11,7 +11,7 @@ import getTimeString from 'lib/getTimeString';
import { isEqual } from 'lodash-es';
import isEmpty from 'lodash-es/isEmpty';
import { useDashboard } from 'providers/Dashboard/Dashboard';
-import { memo, useEffect, useRef, useState } from 'react';
+import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useQueryClient } from 'react-query';
import { useDispatch, useSelector } from 'react-redux';
import { UpdateTimeInterval } from 'store/actions';
@@ -27,6 +27,7 @@ import { GridCardGraphProps } from './types';
import { isDataAvailableByPanelType } from './utils';
import WidgetGraphComponent from './WidgetGraphComponent';
+// eslint-disable-next-line sonarjs/cognitive-complexity
function GridCardGraph({
widget,
headerMenuList = [MenuItemKeys.View],
@@ -188,12 +189,23 @@ function GridCardGraph({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [updatedQuery]);
+ const isLogsQuery = useMemo(
+ () =>
+ requestData.query.builder.queryData.every(
+ (query) => query.dataSource === DataSource.LOGS,
+ ),
+ [requestData.query],
+ );
+
const queryResponse = useGetQueryRange(
{
...requestData,
variables: getDashboardVariables(variables),
selectedTime: widget.timePreferance || 'GLOBAL_TIME',
- globalSelectedInterval,
+ globalSelectedInterval:
+ widget.panelTypes === PANEL_TYPES.LIST && isLogsQuery
+ ? 'custom'
+ : globalSelectedInterval,
start: customTimeRange?.startTime || start,
end: customTimeRange?.endTime || end,
},
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/EntityEvents.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/EntityEvents.tsx
index 67b4722ba3..70e02902c9 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/EntityEvents.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityEvents/EntityEvents.tsx
@@ -7,6 +7,7 @@ import { DEFAULT_ENTITY_VERSION } from 'constants/app';
import { EventContents } from 'container/InfraMonitoringK8s/commonUtils';
import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
import LoadingContainer from 'container/InfraMonitoringK8s/LoadingContainer';
+import { INITIAL_PAGE_SIZE } from 'container/LogsContextList/configs';
import LogsError from 'container/LogsError/LogsError';
import { ORDERBY_FILTERS } from 'container/QueryBuilder/filters/OrderByFilter/config';
import QueryBuilderSearch from 'container/QueryBuilder/filters/QueryBuilderSearch';
@@ -21,10 +22,8 @@ import { isArray } from 'lodash-es';
import { ChevronDown, ChevronLeft, ChevronRight, Loader2 } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { useQuery } from 'react-query';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
-import { v4 } from 'uuid';
import {
EntityDetailsEmptyContainer,
@@ -123,16 +122,19 @@ export default function Events({
filters,
);
- basePayload.query.builder.queryData[0].pageSize = 10;
+ basePayload.query.builder.queryData[0].pageSize = INITIAL_PAGE_SIZE;
+ basePayload.query.builder.queryData[0].offset =
+ (page - 1) * INITIAL_PAGE_SIZE;
basePayload.query.builder.queryData[0].orderBy = [
{ columnName: 'timestamp', order: ORDERBY_FILTERS.DESC },
+ { columnName: 'id', order: ORDERBY_FILTERS.DESC },
];
return basePayload;
- }, [timeRange.startTime, timeRange.endTime, filters]);
+ }, [timeRange.startTime, timeRange.endTime, filters, page]);
const { data: eventsData, isLoading, isFetching, isError } = useQuery({
- queryKey: [queryKey, timeRange.startTime, timeRange.endTime, filters],
+ queryKey: [queryKey, timeRange.startTime, timeRange.endTime, filters, page],
queryFn: () => GetMetricQueryRange(queryPayload, DEFAULT_ENTITY_VERSION),
enabled: !!queryPayload,
});
@@ -189,61 +191,12 @@ export default function Events({
const handlePrev = (): void => {
if (!formattedEntityEvents.length) return;
-
setPage(page - 1);
-
- const firstEvent = formattedEntityEvents[0];
-
- const newItems = [
- ...filters.items.filter((item) => item.key?.key !== 'id'),
- {
- id: v4(),
- key: {
- key: 'id',
- type: '',
- dataType: DataTypes.String,
- isColumn: true,
- },
- op: '>',
- value: firstEvent.id,
- },
- ];
-
- const newFilters = {
- op: 'AND',
- items: newItems,
- } as IBuilderQuery['filters'];
-
- handleChangeEventFilters(newFilters);
};
const handleNext = (): void => {
if (!formattedEntityEvents.length) return;
-
setPage(page + 1);
- const lastEvent = formattedEntityEvents[formattedEntityEvents.length - 1];
-
- const newItems = [
- ...filters.items.filter((item) => item.key?.key !== 'id'),
- {
- id: v4(),
- key: {
- key: 'id',
- type: '',
- dataType: DataTypes.String,
- isColumn: true,
- },
- op: '<',
- value: lastEvent.id,
- },
- ];
-
- const newFilters = {
- op: 'AND',
- items: newItems,
- } as IBuilderQuery['filters'];
-
- handleChangeEventFilters(newFilters);
};
const handleExpandRowIcon = ({
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogs.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogs.tsx
index c73865eb80..919559c795 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogs.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogs.tsx
@@ -9,19 +9,13 @@ import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
import LogsError from 'container/LogsError/LogsError';
import { LogsLoading } from 'container/LogsLoading/LogsLoading';
import { FontSize } from 'container/OptionsMenu/types';
-import { ORDERBY_FILTERS } from 'container/QueryBuilder/filters/OrderByFilter/config';
+import { useHandleLogsPagination } from 'hooks/infraMonitoring/useHandleLogsPagination';
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
-import { isEqual } from 'lodash-es';
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo } from 'react';
import { useQuery } from 'react-query';
import { Virtuoso } from 'react-virtuoso';
import { ILog } from 'types/api/logs/log';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import {
- IBuilderQuery,
- TagFilterItem,
-} from 'types/api/queryBuilder/queryBuilderData';
-import { v4 } from 'uuid';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import {
EntityDetailsEmptyContainer,
@@ -33,7 +27,6 @@ interface Props {
startTime: number;
endTime: number;
};
- handleChangeLogFilters: (filters: IBuilderQuery['filters']) => void;
filters: IBuilderQuery['filters'];
queryKey: string;
category: K8sCategory;
@@ -42,87 +35,33 @@ interface Props {
function EntityLogs({
timeRange,
- handleChangeLogFilters,
filters,
queryKey,
category,
queryKeyFilters,
}: Props): JSX.Element {
- const [logs, setLogs] = useState<ILog[]>([]);
- const [hasReachedEndOfLogs, setHasReachedEndOfLogs] = useState(false);
- const [restFilters, setRestFilters] = useState<TagFilterItem[]>([]);
- const [resetLogsList, setResetLogsList] = useState<boolean>(false);
-
- useEffect(() => {
- const newRestFilters = filters.items.filter(
- (item) =>
- item.key?.key !== 'id' && !queryKeyFilters.includes(item.key?.key ?? ''),
- );
-
- const areFiltersSame = isEqual(restFilters, newRestFilters);
-
- if (!areFiltersSame) {
- setResetLogsList(true);
- }
-
- setRestFilters(newRestFilters);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [filters]);
-
- const queryPayload = useMemo(() => {
- const basePayload = getEntityEventsOrLogsQueryPayload(
- timeRange.startTime,
- timeRange.endTime,
- filters,
- );
-
- basePayload.query.builder.queryData[0].pageSize = 100;
- basePayload.query.builder.queryData[0].orderBy = [
- { columnName: 'timestamp', order: ORDERBY_FILTERS.DESC },
- ];
-
- return basePayload;
- }, [timeRange.startTime, timeRange.endTime, filters]);
-
- const [isPaginating, setIsPaginating] = useState(false);
+ const basePayload = getEntityEventsOrLogsQueryPayload(
+ timeRange.startTime,
+ timeRange.endTime,
+ filters,
+ );
- const { data, isLoading, isFetching, isError } = useQuery({
- queryKey: [queryKey, timeRange.startTime, timeRange.endTime, filters],
- queryFn: () => GetMetricQueryRange(queryPayload, DEFAULT_ENTITY_VERSION),
- enabled: !!queryPayload,
- keepPreviousData: isPaginating,
+ const {
+ logs,
+ hasReachedEndOfLogs,
+ isPaginating,
+ currentPage,
+ setIsPaginating,
+ handleNewData,
+ loadMoreLogs,
+ queryPayload,
+ } = useHandleLogsPagination({
+ timeRange,
+ filters,
+ queryKeyFilters,
+ basePayload,
});
- useEffect(() => {
- if (data?.payload?.data?.newResult?.data?.result) {
- const currentData = data.payload.data.newResult.data.result;
-
- if (resetLogsList) {
- const currentLogs: ILog[] =
- currentData[0].list?.map((item) => ({
- ...item.data,
- timestamp: item.timestamp,
- })) || [];
-
- setLogs(currentLogs);
-
- setResetLogsList(false);
- }
-
- if (currentData.length > 0 && currentData[0].list) {
- const currentLogs: ILog[] =
- currentData[0].list.map((item) => ({
- ...item.data,
- timestamp: item.timestamp,
- })) || [];
-
- setLogs((prev) => [...prev, ...currentLogs]);
- } else {
- setHasReachedEndOfLogs(true);
- }
- }
- }, [data, restFilters, isPaginating, resetLogsList]);
-
const getItemContent = useCallback(
(_: number, logToRender: ILog): JSX.Element => (
<RawLogView
@@ -149,38 +88,28 @@ function EntityLogs({
[],
);
- const loadMoreLogs = useCallback(() => {
- if (!logs.length) return;
-
- setIsPaginating(true);
- const lastLog = logs[logs.length - 1];
-
- const newItems = [
- ...filters.items.filter((item) => item.key?.key !== 'id'),
- {
- id: v4(),
- key: {
- key: 'id',
- type: '',
- dataType: DataTypes.String,
- isColumn: true,
- },
- op: '<',
- value: lastLog.id,
- },
- ];
-
- const newFilters = {
- op: 'AND',
- items: newItems,
- } as IBuilderQuery['filters'];
+ const { data, isLoading, isFetching, isError } = useQuery({
+ queryKey: [
+ queryKey,
+ timeRange.startTime,
+ timeRange.endTime,
+ filters,
+ currentPage,
+ ],
+ queryFn: () => GetMetricQueryRange(queryPayload, DEFAULT_ENTITY_VERSION),
+ enabled: !!queryPayload,
+ keepPreviousData: isPaginating,
+ });
- handleChangeLogFilters(newFilters);
- }, [logs, filters, handleChangeLogFilters]);
+ useEffect(() => {
+ if (data?.payload?.data?.newResult?.data?.result) {
+ handleNewData(data.payload.data.newResult.data.result);
+ }
+ }, [data, handleNewData]);
useEffect(() => {
setIsPaginating(false);
- }, [data]);
+ }, [data, setIsPaginating]);
const renderFooter = useCallback(
(): JSX.Element | null => (
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogsDetailedView.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogsDetailedView.tsx
index 737f867ded..e2f071956d 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogsDetailedView.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/EntityLogsDetailedView.tsx
@@ -97,7 +97,6 @@ function EntityLogsDetailedView({
</div>
<EntityLogs
timeRange={timeRange}
- handleChangeLogFilters={handleChangeLogFilters}
filters={logFilters}
queryKey={queryKey}
category={category}
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/__tests__/EntityLogs.test.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/__tests__/EntityLogs.test.tsx
new file mode 100644
index 0000000000..3d2ae995c6
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/EntityLogs/__tests__/EntityLogs.test.tsx
@@ -0,0 +1,179 @@
+import { ENVIRONMENT } from 'constants/env';
+import { K8sCategory } from 'container/InfraMonitoringK8s/constants';
+import {
+ verifyFiltersAndOrderBy,
+ verifyPayload,
+} from 'container/LogsExplorerViews/tests/LogsExplorerPagination.test';
+import { logsPaginationQueryRangeSuccessResponse } from 'mocks-server/__mockdata__/logs_query_range';
+import { server } from 'mocks-server/server';
+import { rest } from 'msw';
+import { VirtuosoMockContext } from 'react-virtuoso';
+import {
+ act,
+ fireEvent,
+ render,
+ RenderResult,
+ screen,
+ waitFor,
+} from 'tests/test-utils';
+import { QueryRangePayload } from 'types/api/metrics/getQueryRange';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+
+import EntityLogs from '../EntityLogs';
+
+jest.mock('uplot', () => {
+ const paths = {
+ spline: jest.fn(),
+ bars: jest.fn(),
+ };
+ const uplotMock = jest.fn(() => ({
+ paths,
+ }));
+ return {
+ paths,
+ default: uplotMock,
+ };
+});
+
+jest.mock(
+ 'components/OverlayScrollbar/OverlayScrollbar',
+ () =>
+ function MockOverlayScrollbar({
+ children,
+ }: {
+ children: React.ReactNode;
+ }): JSX.Element {
+ return <div>{children}</div>;
+ },
+);
+
+describe('EntityLogs', () => {
+ let capturedQueryRangePayloads: QueryRangePayload[] = [];
+ const itemHeight = 100;
+
+ beforeEach(() => {
+ server.use(
+ rest.post(
+ `${ENVIRONMENT.baseURL}/api/v3/query_range`,
+ async (req, res, ctx) => {
+ capturedQueryRangePayloads.push(await req.json());
+
+ const lastPayload =
+ capturedQueryRangePayloads[capturedQueryRangePayloads.length - 1];
+
+ const queryData = lastPayload?.compositeQuery.builderQueries
+ ?.A as IBuilderQuery;
+
+ const offset = queryData?.offset ?? 0;
+ return res(
+ ctx.status(200),
+ ctx.json(logsPaginationQueryRangeSuccessResponse({ offset })),
+ );
+ },
+ ),
+ );
+ capturedQueryRangePayloads = [];
+ });
+ it('should check if k8s logs pagination flows work properly', async () => {
+ let renderResult: RenderResult;
+ let scrollableElement: HTMLElement;
+
+ act(() => {
+ renderResult = render(
+ <VirtuosoMockContext.Provider value={{ viewportHeight: 500, itemHeight }}>
+ <EntityLogs
+ timeRange={{ startTime: 1, endTime: 2 }}
+ filters={{ items: [], op: 'AND' }}
+ queryKey="test"
+ category={K8sCategory.PODS}
+ queryKeyFilters={[]}
+ />
+ </VirtuosoMockContext.Provider>,
+ );
+ });
+
+ await waitFor(() => {
+ expect(
+ screen.queryByText('pending_data_placeholder'),
+ ).not.toBeInTheDocument();
+ });
+
+ await waitFor(() => {
+ expect(capturedQueryRangePayloads.length).toBe(1);
+ });
+
+ await waitFor(async () => {
+ // Find the Virtuoso scroller element by its data-test-id
+ scrollableElement = renderResult.container.querySelector(
+ '[data-test-id="virtuoso-scroller"]',
+ ) as HTMLElement;
+
+ // Ensure the element exists
+ expect(scrollableElement).not.toBeNull();
+
+ if (scrollableElement) {
+ // Set the scrollTop property to simulate scrolling to the calculated end position
+ scrollableElement.scrollTop = 99 * itemHeight;
+
+ act(() => {
+ fireEvent.scroll(scrollableElement);
+ });
+ }
+ });
+
+ await waitFor(() => {
+ expect(capturedQueryRangePayloads.length).toBe(2);
+ });
+
+ const firstPayload = capturedQueryRangePayloads[0];
+ verifyPayload({
+ payload: firstPayload,
+ expectedOffset: 0,
+ });
+
+ // Store the time range from the first payload, which should be consistent in subsequent requests
+ const initialTimeRange = {
+ start: firstPayload.start,
+ end: firstPayload.end,
+ };
+
+ const secondPayload = capturedQueryRangePayloads[1];
+ const secondQueryData = verifyPayload({
+ payload: secondPayload,
+ expectedOffset: 100,
+ initialTimeRange,
+ });
+ verifyFiltersAndOrderBy(secondQueryData);
+
+ await waitFor(async () => {
+ // Find the Virtuoso scroller element by its data-test-id
+ scrollableElement = renderResult.container.querySelector(
+ '[data-test-id="virtuoso-scroller"]',
+ ) as HTMLElement;
+
+ // Ensure the element exists
+ expect(scrollableElement).not.toBeNull();
+
+ if (scrollableElement) {
+ // Set the scrollTop property to simulate scrolling to the calculated end position
+ scrollableElement.scrollTop = 199 * itemHeight;
+
+ act(() => {
+ fireEvent.scroll(scrollableElement);
+ });
+ }
+ });
+
+ await waitFor(() => {
+ expect(capturedQueryRangePayloads.length).toBeGreaterThanOrEqual(3);
+ });
+
+ const thirdPayload = capturedQueryRangePayloads[2];
+ const thirdQueryData = verifyPayload({
+ payload: thirdPayload,
+ expectedOffset: 200,
+ initialTimeRange,
+ });
+ verifyFiltersAndOrderBy(thirdQueryData);
+ });
+});
diff --git a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/utils.tsx b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/utils.tsx
index 24dac98376..c7c25ee144 100644
--- a/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/utils.tsx
+++ b/frontend/src/container/InfraMonitoringK8s/EntityDetailsUtils/utils.tsx
@@ -85,9 +85,6 @@ export const getEntityEventsOrLogsQueryPayload = (
id: uuidv4(),
queryType: EQueryType.QUERY_BUILDER,
},
- params: {
- lastLogLineTimestamp: null,
- },
start,
end,
});
diff --git a/frontend/src/container/LogDetailedView/ContextView/__tests__/ContextLogRenderer.test.tsx b/frontend/src/container/LogDetailedView/ContextView/__tests__/ContextLogRenderer.test.tsx
index 32b2b6d718..c4c90fc298 100644
--- a/frontend/src/container/LogDetailedView/ContextView/__tests__/ContextLogRenderer.test.tsx
+++ b/frontend/src/container/LogDetailedView/ContextView/__tests__/ContextLogRenderer.test.tsx
@@ -17,6 +17,8 @@ import { Provider } from 'react-redux';
import { MemoryRouter } from 'react-router-dom';
import { VirtuosoMockContext } from 'react-virtuoso';
import store from 'store';
+import { QueryRangePayload } from 'types/api/metrics/getQueryRange';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import ContextLogRenderer from '../ContextLogRenderer';
import {
@@ -58,6 +60,18 @@ jest.mock('hooks/useSafeNavigate', () => ({
}),
}));
+jest.mock(
+ 'components/OverlayScrollbar/OverlayScrollbar',
+ () =>
+ function MockOverlayScrollbar({
+ children,
+ }: {
+ children: React.ReactNode;
+ }): JSX.Element {
+ return <div>{children}</div>;
+ },
+);
+
// Common wrapper component for tests
const renderContextLogRenderer = (): RenderResult => {
const defaultProps = {
@@ -99,6 +113,8 @@ const renderContextLogRenderer = (): RenderResult => {
};
describe('ContextLogRenderer', () => {
+ let capturedQueryRangePayload: QueryRangePayload;
+
beforeEach(() => {
server.use(
rest.get(`${ENVIRONMENT.baseURL}/api/v1/logs`, (req, res, ctx) =>
@@ -106,8 +122,12 @@ describe('ContextLogRenderer', () => {
),
);
server.use(
- rest.post(`${ENVIRONMENT.baseURL}/api/v3/query_range`, (req, res, ctx) =>
- res(ctx.status(200), ctx.json(mockQueryRangeResponse)),
+ rest.post(
+ `${ENVIRONMENT.baseURL}/api/v3/query_range`,
+ async (req, res, ctx) => {
+ capturedQueryRangePayload = await req.json();
+ return res(ctx.status(200), ctx.json(mockQueryRangeResponse));
+ },
),
);
});
@@ -142,4 +162,99 @@ describe('ContextLogRenderer', () => {
expect(screen.getAllByText(/Failed to authenticate/)).toHaveLength(3);
});
});
+
+ describe('pagination behavior', () => {
+ let loadMoreButtons: HTMLElement[];
+ let initialPayload: {
+ start: number;
+ end: number;
+ compositeQuery: {
+ builderQueries: {
+ A: IBuilderQuery;
+ };
+ };
+ };
+
+ beforeEach(async () => {
+ await act(async () => {
+ renderContextLogRenderer();
+ });
+
+ await waitFor(() => {
+ expect(screen.getAllByText('Load more')).toHaveLength(2);
+ expect(screen.getByText(/Test log message/)).toBeInTheDocument();
+ });
+
+ loadMoreButtons = screen.getAllByText('Load more');
+
+ // Capture initial query payload
+ const { start, end, ...rest } = capturedQueryRangePayload;
+ initialPayload = {
+ start,
+ end,
+ compositeQuery: rest.compositeQuery as any,
+ };
+ });
+
+ enum LoadMoreButtonIndex {
+ PREV = 0,
+ NEXT = 1,
+ }
+
+ const verifyPaginationBehavior = async (
+ buttonIndex: LoadMoreButtonIndex,
+ expectedOpChange: { before: string; after: string },
+ ): Promise<void> => {
+ const initialBuilderQuery = initialPayload.compositeQuery.builderQueries
+ .A as IBuilderQuery;
+
+ // Click the load more button (previous or next)
+ await act(async () => {
+ await userEvent.click(loadMoreButtons[buttonIndex]);
+ });
+
+ // Extract and verify the updated query
+ const {
+ start: afterStart,
+ end: afterEnd,
+ ...afterPayload
+ } = capturedQueryRangePayload;
+ const afterBuilderQuery = afterPayload.compositeQuery.builderQueries
+ ?.A as IBuilderQuery;
+
+ // Verify timestamps remain constant
+ expect(afterStart).toEqual(initialPayload.start);
+ expect(afterEnd).toEqual(initialPayload.end);
+
+ // Verify offset changes
+ expect(initialBuilderQuery.offset).toEqual(0);
+ expect(afterBuilderQuery.offset).toEqual(10);
+
+ // Verify operator changes
+ expect(initialBuilderQuery.filters.items[0].op).toEqual(
+ expectedOpChange.before,
+ );
+ expect(afterBuilderQuery.filters.items[0].op).toEqual(
+ expectedOpChange.after,
+ );
+
+ // Verify filter structure remains consistent
+ expect(initialBuilderQuery.filters.items.length).toEqual(
+ afterBuilderQuery.filters.items.length,
+ );
+ expect(initialBuilderQuery.filters.items[0]?.key?.key).toEqual('id');
+ expect(afterBuilderQuery.filters.items[0]?.key?.key).toEqual('id');
+ };
+
+ it('should keep the start and end timestamps constant on clicking load more (prev / next) pages', async () => {
+ await verifyPaginationBehavior(LoadMoreButtonIndex.PREV, {
+ before: '<',
+ after: '>',
+ });
+ await verifyPaginationBehavior(LoadMoreButtonIndex.NEXT, {
+ before: '<',
+ after: '<',
+ });
+ });
+ });
});
diff --git a/frontend/src/container/LogDetailedView/ContextView/useContextLogData.ts b/frontend/src/container/LogDetailedView/ContextView/useContextLogData.ts
index 427834cd64..afbd7bb7cc 100644
--- a/frontend/src/container/LogDetailedView/ContextView/useContextLogData.ts
+++ b/frontend/src/container/LogDetailedView/ContextView/useContextLogData.ts
@@ -136,6 +136,9 @@ export const useContextLogData = ({
},
undefined, // params
false, // isDependentOnQB
+ undefined, // keyRef
+ undefined, // headers
+ 'custom', // selectedTimeInterval
);
const handleShowNextLines = useCallback(() => {
diff --git a/frontend/src/container/LogsExplorerViews/index.tsx b/frontend/src/container/LogsExplorerViews/index.tsx
index 0009fc405e..d92457ae43 100644
--- a/frontend/src/container/LogsExplorerViews/index.tsx
+++ b/frontend/src/container/LogsExplorerViews/index.tsx
@@ -41,7 +41,7 @@ import { useNotifications } from 'hooks/useNotifications';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQueryData from 'hooks/useUrlQueryData';
import { FlatLogData } from 'lib/logs/flatLogData';
-import { getPaginationQueryData } from 'lib/newQueryBuilder/getPaginationQueryData';
+import { getPaginationQueryDataV2 } from 'lib/newQueryBuilder/getPaginationQueryData';
import {
cloneDeep,
defaultTo,
@@ -69,7 +69,6 @@ import { ILog } from 'types/api/logs/log';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import {
IBuilderQuery,
- OrderByPayload,
Query,
TagFilter,
} from 'types/api/queryBuilder/queryBuilderData';
@@ -94,7 +93,9 @@ function LogsExplorerViews({
selectedView: SELECTED_VIEWS;
showFrequencyChart: boolean;
setIsLoadingQueries: React.Dispatch<React.SetStateAction<boolean>>;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
listQueryKeyRef: MutableRefObject<any>;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
chartQueryKeyRef: MutableRefObject<any>;
}): JSX.Element {
const { notifications } = useNotifications();
@@ -135,9 +136,6 @@ function LogsExplorerViews({
// State
const [page, setPage] = useState<number>(1);
const [logs, setLogs] = useState<ILog[]>([]);
- const [lastLogLineTimestamp, setLastLogLineTimestamp] = useState<
- number | string | null
- >();
const [requestData, setRequestData] = useState<Query | null>(null);
const [showFormatMenuItems, setShowFormatMenuItems] = useState(false);
const [queryId, setQueryId] = useState<string>(v4());
@@ -157,14 +155,6 @@ function LogsExplorerViews({
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
});
- const orderByTimestamp: OrderByPayload | null = useMemo(() => {
- const timestampOrderBy = listQuery?.orderBy.find(
- (item) => item.columnName === 'timestamp',
- );
-
- return timestampOrderBy || null;
- }, [listQuery]);
-
const isMultipleQueries = useMemo(
() =>
currentQuery.builder.queryData.length > 1 ||
@@ -276,14 +266,6 @@ function LogsExplorerViews({
start: minTime,
end: maxTime,
}),
- // send the lastLogTimeStamp only when the panel type is list and the orderBy is timestamp and the order is desc
- lastLogLineTimestamp:
- panelType === PANEL_TYPES.LIST &&
- requestData?.builder?.queryData?.[0]?.orderBy?.[0]?.columnName ===
- 'timestamp' &&
- requestData?.builder?.queryData?.[0]?.orderBy?.[0]?.order === 'desc'
- ? lastLogLineTimestamp
- : undefined,
},
undefined,
listQueryKeyRef,
@@ -291,6 +273,8 @@ function LogsExplorerViews({
...(!isEmpty(queryId) &&
selectedPanelType !== PANEL_TYPES.LIST && { 'X-SIGNOZ-QUERY-ID': queryId }),
},
+ // custom selected time interval to prevent recalculating the start and end timestamps before fetching next pages
+ 'custom',
);
const getRequestData = useCallback(
@@ -298,17 +282,13 @@ function LogsExplorerViews({
query: Query | null,
params: {
page: number;
- log: ILog | null;
pageSize: number;
filters: TagFilter;
},
): Query | null => {
if (!query) return null;
- const paginateData = getPaginationQueryData({
- filters: params.filters,
- listItemId: params.log ? params.log.id : null,
- orderByTimestamp,
+ const paginateData = getPaginationQueryDataV2({
page: params.page,
pageSize: params.pageSize,
});
@@ -357,53 +337,34 @@ function LogsExplorerViews({
return data;
},
- [orderByTimestamp, listQuery, activeLogId],
+ [listQuery, activeLogId],
);
- const handleEndReached = useCallback(
- (index: number) => {
- if (!listQuery) return;
-
- if (isLimit) return;
- if (logs.length < pageSize) return;
+ const handleEndReached = useCallback(() => {
+ if (!listQuery) return;
- const { limit, filters } = listQuery;
+ if (isLimit) return;
+ if (logs.length < pageSize) return;
- const lastLog = logs[index];
+ const { limit, filters } = listQuery;
- const nextLogsLength = logs.length + pageSize;
+ const nextLogsLength = logs.length + pageSize;
- const nextPageSize =
- limit && nextLogsLength >= limit ? limit - logs.length : pageSize;
+ const nextPageSize =
+ limit && nextLogsLength >= limit ? limit - logs.length : pageSize;
- if (!stagedQuery) return;
+ if (!stagedQuery) return;
- const newRequestData = getRequestData(stagedQuery, {
- filters,
- page: page + 1,
- log: orderByTimestamp ? lastLog : null,
- pageSize: nextPageSize,
- });
+ const newRequestData = getRequestData(stagedQuery, {
+ filters,
+ page: page + 1,
+ pageSize: nextPageSize,
+ });
- // initialise the last log timestamp to null as we don't have the logs.
- // as soon as we scroll to the end of the logs we set the lastLogLineTimestamp to the last log timestamp.
- setLastLogLineTimestamp(lastLog.timestamp);
+ setPage((prevPage) => prevPage + 1);
- setPage((prevPage) => prevPage + 1);
-
- setRequestData(newRequestData);
- },
- [
- isLimit,
- logs,
- listQuery,
- pageSize,
- stagedQuery,
- getRequestData,
- page,
- orderByTimestamp,
- ],
- );
+ setRequestData(newRequestData);
+ }, [isLimit, logs, listQuery, pageSize, stagedQuery, getRequestData, page]);
useEffect(() => {
setQueryId(v4());
@@ -575,11 +536,6 @@ function LogsExplorerViews({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data]);
- useEffect(() => {
- // clear the lastLogLineTimestamp when the data changes
- setLastLogLineTimestamp(null);
- }, [data]);
-
useEffect(() => {
if (
requestData?.id !== stagedQuery?.id ||
@@ -588,7 +544,6 @@ function LogsExplorerViews({
const newRequestData = getRequestData(stagedQuery, {
filters: listQuery?.filters || initialFilters,
page: 1,
- log: null,
pageSize,
});
diff --git a/frontend/src/container/LogsExplorerViews/tests/LogsExplorerPagination.test.tsx b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerPagination.test.tsx
new file mode 100644
index 0000000000..a437acf42e
--- /dev/null
+++ b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerPagination.test.tsx
@@ -0,0 +1,301 @@
+import ROUTES from 'constants/routes';
+import {
+ logsPaginationQueryRangeSuccessResponse,
+ PAGE_SIZE,
+} from 'mocks-server/__mockdata__/logs_query_range';
+import { server } from 'mocks-server/server';
+import { rest } from 'msw';
+import LogsExplorer from 'pages/LogsExplorer';
+import React from 'react';
+import { I18nextProvider } from 'react-i18next';
+import { VirtuosoMockContext } from 'react-virtuoso';
+import i18n from 'ReactI18';
+import {
+ act,
+ fireEvent,
+ render,
+ RenderResult,
+ screen,
+ waitFor,
+} from 'tests/test-utils';
+import { QueryRangePayload } from 'types/api/metrics/getQueryRange';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+
+const API_ENDPOINT = 'http://localhost/api/v4/query_range';
+
+jest.mock('uplot', () => {
+ const paths = {
+ spline: jest.fn(),
+ bars: jest.fn(),
+ };
+ const uplotMock = jest.fn(() => ({
+ paths,
+ }));
+ return {
+ paths,
+ default: uplotMock,
+ };
+});
+
+jest.mock('react-router-dom', () => ({
+ ...jest.requireActual('react-router-dom'),
+ useLocation: (): { search: string; pathname: string } => ({
+ pathname: ROUTES.LOGS_EXPLORER,
+ search:
+ '?compositeQuery=%257B%2522queryType%2522%253A%2522builder%2522%252C%2522builder%2522%253A%257B%2522queryData%2522%253A%255B%257B%2522dataSource%2522%253A%2522logs%2522%252C%2522queryName%2522%253A%2522A%2522%252C%2522aggregateOperator%2522%253A%2522noop%2522%252C%2522aggregateAttribute%2522%253A%257B%2522id%2522%253A%2522------%2522%252C%2522dataType%2522%253A%2522%2522%252C%2522key%2522%253A%2522%2522%252C%2522isColumn%2522%253Afalse%252C%2522type%2522%253A%2522%2522%252C%2522isJSON%2522%253Afalse%257D%252C%2522timeAggregation%2522%253A%2522rate%2522%252C%2522spaceAggregation%2522%253A%2522sum%2522%252C%2522functions%2522%253A%255B%255D%252C%2522filters%2522%253A%257B%2522items%2522%253A%255B%255D%252C%2522op%2522%253A%2522AND%2522%257D%252C%2522expression%2522%253A%2522A%2522%252C%2522disabled%2522%253Afalse%252C%2522stepInterval%2522%253A60%252C%2522having%2522%253A%255B%255D%252C%2522limit%2522%253Anull%252C%2522orderBy%2522%253A%255B%257B%2522columnName%2522%253A%2522timestamp%2522%252C%2522order%2522%253A%2522desc%2522%257D%255D%252C%2522groupBy%2522%253A%255B%255D%252C%2522legend%2522%253A%2522%2522%252C%2522reduceTo%2522%253A%2522avg%2522%257D%255D%252C%2522queryFormulas%2522%253A%255B%255D%257D%252C%2522promql%2522%253A%255B%257B%2522name%2522%253A%2522A%2522%252C%2522query%2522%253A%2522%2522%252C%2522legend%2522%253A%2522%2522%252C%2522disabled%2522%253Afalse%257D%255D%252C%2522clickhouse_sql%2522%253A%255B%257B%2522name%2522%253A%2522A%2522%252C%2522legend%2522%253A%2522%2522%252C%2522disabled%2522%253Afalse%252C%2522query%2522%253A%2522%2522%257D%255D%252C%2522id%2522%253A%25220d764438-8023-44b9-9bab-2f05012eca7b%2522%257D&options=%7B%22selectColumns%22%3A%5B%7B%22key%22%3A%22timestamp%22%2C%22dataType%22%3A%22string%22%2C%22type%22%3A%22tag%22%2C%22isColumn%22%3Atrue%2C%22isJSON%22%3Afalse%2C%22id%22%3A%22timestamp--string--tag--true%22%2C%22isIndexed%22%3Afalse%7D%2C%7B%22key%22%3A%22body%22%2C%22dataType%22%3A%22string%22%2C%22type%22%3A%22tag%22%2C%22isColumn%22%3Atrue%2C%22isJSON%22%3Afalse%2C%22id%22%3A%22body--string--tag--true%22%2C%22isIndexed%22%3Afalse%7D%5D%2C%22maxLines%22%3A2%2C%22format%22%3A%22raw%22%2C%22fontSize%22%3A%22small%22%2C%22version%22%3A1%7D',
+ }),
+}));
+
+jest.mock('hooks/useSafeNavigate', () => ({
+ useSafeNavigate: (): any => ({
+ safeNavigate: jest.fn(),
+ }),
+}));
+
+jest.mock(
+ 'container/TopNav/DateTimeSelectionV2/index.tsx',
+ () =>
+ function MockDateTimeSelection(): JSX.Element {
+ return <div>MockDateTimeSelection</div>;
+ },
+);
+jest.mock(
+ 'container/LogsExplorerChart',
+ () =>
+ function MockLogsExplorerChart(): JSX.Element {
+ return <div>MockLogsExplorerChart</div>;
+ },
+);
+jest.mock(
+ 'container/QueryBuilder/filters/QueryBuilderSearchV2/QueryBuilderSearchV2',
+ () =>
+ function MockQueryBuilderSearchV2(): JSX.Element {
+ return <div>MockQueryBuilderSearchV2</div>;
+ },
+);
+jest.mock(
+ 'container/ExplorerOptions/ExplorerOptionWrapper',
+ () =>
+ function MockExplorerOptionWrapper(): JSX.Element {
+ return <div>MockExplorerOptionWrapper</div>;
+ },
+);
+jest.mock(
+ 'components/QuickFilters/QuickFilters',
+ () =>
+ function MockQuickFilters(): JSX.Element {
+ return <div>MockQuickFilters</div>;
+ },
+);
+
+jest.mock(
+ 'components/OverlayScrollbar/OverlayScrollbar',
+ () =>
+ function MockOverlayScrollbar({
+ children,
+ }: {
+ children: React.ReactNode;
+ }): JSX.Element {
+ return <div>{children}</div>;
+ },
+);
+
+// --- Test Utilities ---
+
+// Helper function to create a mock API response with a given offset
+const createMockResponse = (offset: number): QueryRangePayload =>
+ logsPaginationQueryRangeSuccessResponse({ offset });
+
+const setupServer = (capturedPayloads: QueryRangePayload[]): void => {
+ server.use(
+ rest.post(API_ENDPOINT, async (req, res, ctx) => {
+ const payload = await req.json();
+ // Only capture payloads for the 'list' panel type
+ if (payload.compositeQuery.panelType === 'list') {
+ capturedPayloads.push(payload);
+ }
+ // Get the offset from the latest captured payload
+ const lastPayload = capturedPayloads[capturedPayloads.length - 1];
+ const queryData = lastPayload?.compositeQuery.builderQueries
+ ?.A as IBuilderQuery;
+ const offset = queryData?.offset ?? 0;
+ return res(ctx.status(200), ctx.json(createMockResponse(offset)));
+ }),
+ );
+};
+
+// Helper function to verify properties of a captured payload
+export const verifyPayload = ({
+ payload,
+ expectedOffset,
+ initialTimeRange,
+}: {
+ payload: QueryRangePayload;
+ expectedOffset: number;
+ initialTimeRange?: { start: number; end: number };
+}): IBuilderQuery => {
+ // Extract the builder query data for query name 'A'
+ const queryData = payload.compositeQuery.builderQueries?.A as IBuilderQuery;
+ expect(queryData).toBeDefined();
+ // Assert that the offset in the payload matches the expected offset
+ expect(queryData.offset).toBe(expectedOffset);
+
+ // If initial time range is provided, assert that the payload start and end match
+ if (initialTimeRange) {
+ expect(payload.start).toBe(initialTimeRange.start);
+ expect(payload.end).toBe(initialTimeRange.end);
+ }
+
+ return queryData;
+};
+
+export const verifyFiltersAndOrderBy = (queryData: IBuilderQuery): void => {
+ // Verify that the 'id' filter is not present in the pagination query
+ const thirdIdFilter = queryData.filters?.items?.find(
+ (item) => item?.key?.key === 'id',
+ );
+ expect(thirdIdFilter).toBeUndefined();
+
+ // Verify the sorting order includes 'id' if 'timestamp' is present
+ const OrderByTimestamp = queryData.orderBy?.find(
+ (item) => item.columnName === 'timestamp',
+ );
+ const orderById = queryData.orderBy?.find((item) => item.columnName === 'id');
+
+ if (OrderByTimestamp) {
+ expect(orderById).toBeDefined();
+ // Ensure the 'id' sorting order matches the 'timestamp' sorting order
+ expect(orderById?.order).toBe(OrderByTimestamp.order);
+ }
+};
+
+describe('LogsExplorerViews Pagination', () => {
+ // Array to store captured API request payloads
+ let capturedPayloads: QueryRangePayload[];
+
+ beforeEach(() => {
+ // Use real timers for test setup, especially for server delays
+ jest.useRealTimers();
+ // Reset captured payloads array before each test
+ capturedPayloads = [];
+ // Setup the mock server to intercept and capture requests
+ setupServer(capturedPayloads);
+ });
+
+ afterAll(() => {
+ // Use fake timers after the tests are done.
+ jest.useFakeTimers();
+ // Explicitly set the fake system time if needed by other tests
+ jest.setSystemTime(new Date('2023-10-20'));
+ });
+
+ it('should fetch next page with correct payload when scrolled to end', async () => {
+ let renderResult: RenderResult;
+ // Define item height and viewport height for Virtuoso mock
+ const itemHeight = 100;
+ const viewportHeight = 500;
+ // Get the initial number of items from the mock response
+ const initialItemCount = PAGE_SIZE;
+
+ // Calculate the scroll position needed to reach the end of the initial list
+ const totalHeight = initialItemCount * itemHeight;
+ const targetScrollTop = totalHeight - viewportHeight;
+ let scrollableElement: HTMLElement;
+
+ act(() => {
+ renderResult = render(
+ <VirtuosoMockContext.Provider value={{ viewportHeight, itemHeight }}>
+ <I18nextProvider i18n={i18n}>
+ <LogsExplorer />
+ </I18nextProvider>
+ </VirtuosoMockContext.Provider>,
+ );
+ });
+
+ // Wait for the initial data load to complete (pending_data_placeholder disappears)
+ await waitFor(() => {
+ expect(
+ screen.queryByText('pending_data_placeholder'),
+ ).not.toBeInTheDocument();
+ expect(capturedPayloads.length).toBe(1);
+ });
+
+ // Verify the payload of the first call, expecting offset 0
+ const firstPayload = capturedPayloads[0];
+ verifyPayload({ payload: firstPayload, expectedOffset: 0 });
+
+ // Wait for the scrollable element to be available and simulate scrolling
+ await waitFor(async () => {
+ // Find the Virtuoso scroller element by its data-test-id
+ scrollableElement = renderResult.container.querySelector(
+ '[data-test-id="virtuoso-scroller"]',
+ ) as HTMLElement;
+
+ // Ensure the element exists
+ expect(scrollableElement).not.toBeNull();
+
+ if (scrollableElement) {
+ // Set the scrollTop property to simulate scrolling to the calculated end position
+ scrollableElement.scrollTop = targetScrollTop;
+
+ act(() => {
+ fireEvent.scroll(scrollableElement);
+ });
+ }
+ });
+
+ // Verify the second page request was made
+ // Wait for the second API call to be captured after the scroll
+ await waitFor(() => {
+ expect(capturedPayloads.length).toBe(2);
+ });
+
+ // Store the time range from the first payload, which should be consistent in subsequent requests
+ const initialTimeRange = {
+ start: firstPayload.start,
+ end: firstPayload.end,
+ };
+
+ // Verify the payload of the second call, expecting offset 100 and consistent time range
+ const secondPayload = capturedPayloads[1];
+ const secondQueryData = verifyPayload({
+ payload: secondPayload,
+ expectedOffset: 100,
+ initialTimeRange,
+ });
+ verifyFiltersAndOrderBy(secondQueryData);
+
+ // Simulate the second scroll to load the third page
+ await waitFor(async () => {
+ // Calculate the total height assuming two pages are loaded
+ const totalHeightAfterSecondLoad = 2 * initialItemCount * itemHeight;
+
+ // Calculate the scroll position needed to trigger the load of the next page
+ const targetScrollTopAfterSecondLoad =
+ totalHeightAfterSecondLoad - viewportHeight;
+
+ // Simulate scrolling towards the end of the now larger scrollable area
+ scrollableElement.scrollTop = targetScrollTopAfterSecondLoad;
+
+ // Fire the scroll event
+ act(() => {
+ fireEvent.scroll(scrollableElement);
+ });
+ });
+
+ // Verify the third page request was made
+ // Wait for the third API call to be captured
+ await waitFor(() => {
+ expect(capturedPayloads.length).toBe(3);
+ });
+ const thirdPayload = capturedPayloads[2];
+ // Verify the payload of the third call, expecting offset 200 and consistent time range
+ const thirdQueryData = verifyPayload({
+ payload: thirdPayload,
+ expectedOffset: 200,
+ initialTimeRange,
+ });
+
+ verifyFiltersAndOrderBy(thirdQueryData);
+ });
+});
diff --git a/frontend/src/container/LogsPanelTable/LogsPanelComponent.tsx b/frontend/src/container/LogsPanelTable/LogsPanelComponent.tsx
index 5381b9923a..7c55de0bfd 100644
--- a/frontend/src/container/LogsPanelTable/LogsPanelComponent.tsx
+++ b/frontend/src/container/LogsPanelTable/LogsPanelComponent.tsx
@@ -10,7 +10,6 @@ import Controls from 'container/Controls';
import { PER_PAGE_OPTIONS } from 'container/TracesExplorer/ListView/configs';
import { tableStyles } from 'container/TracesExplorer/ListView/styles';
import { useActiveLog } from 'hooks/logs/useActiveLog';
-import { Pagination } from 'hooks/queryPagination';
import { useLogsData } from 'hooks/useLogsData';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { FlatLogData } from 'lib/logs/flatLogData';
@@ -21,46 +20,27 @@ import {
HTMLAttributes,
SetStateAction,
useCallback,
- useEffect,
useMemo,
useState,
} from 'react';
import { UseQueryResult } from 'react-query';
import { SuccessResponse } from 'types/api';
import { Widgets } from 'types/api/dashboard/getAll';
-import { ILog } from 'types/api/logs/log';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
-import { getLogPanelColumnsList, getNextOrPreviousItems } from './utils';
+import { getLogPanelColumnsList } from './utils';
function LogsPanelComponent({
widget,
setRequestData,
queryResponse,
}: LogsPanelComponentProps): JSX.Element {
- const [pagination, setPagination] = useState<Pagination>({
- offset: 0,
- limit: widget.query.builder.queryData[0].limit || 0,
- });
-
- useEffect(() => {
- setRequestData((prev) => ({
- ...prev,
- tableParams: {
- pagination,
- },
- }));
- }, [pagination, setRequestData]);
-
const [pageSize, setPageSize] = useState<number>(10);
+ const [offset, setOffset] = useState<number>(0);
const handleChangePageSize = (value: number): void => {
- setPagination({
- ...pagination,
- limit: 0,
- offset: value,
- });
setPageSize(value);
+ setOffset(0);
setRequestData((prev) => {
const newQueryData = { ...prev.query };
newQueryData.builder.queryData[0].pageSize = value;
@@ -70,7 +50,7 @@ function LogsPanelComponent({
tableParams: {
pagination: {
limit: 0,
- offset: value,
+ offset: 0,
},
},
};
@@ -93,22 +73,12 @@ function LogsPanelComponent({
queryResponse.data?.payload?.data?.newResult?.data?.result[0]?.list?.length;
const totalCount = useMemo(() => dataLength || 0, [dataLength]);
- const [firstLog, setFirstLog] = useState<ILog>();
- const [lastLog, setLastLog] = useState<ILog>();
-
const { logs } = useLogsData({
result: queryResponse.data?.payload?.data?.newResult?.data?.result,
panelType: PANEL_TYPES.LIST,
stagedQuery: widget.query,
});
- useEffect(() => {
- if (logs.length) {
- setFirstLog(logs[0]);
- setLastLog(logs[logs.length - 1]);
- }
- }, [logs]);
-
const flattenLogData = useMemo(
() => logs.map((log) => FlatLogData(log) as RowData),
[logs],
@@ -132,84 +102,27 @@ function LogsPanelComponent({
[logs, onSetActiveLog],
);
- const isOrderByTimeStamp =
- widget.query.builder.queryData[0].orderBy.length > 0 &&
- widget.query.builder.queryData[0].orderBy[0].columnName === 'timestamp';
+ const handleRequestData = (newOffset: number): void => {
+ setOffset(newOffset);
+ setRequestData((prev) => ({
+ ...prev,
+ tableParams: {
+ pagination: {
+ limit: widget.query.builder.queryData[0].limit || 0,
+ offset: newOffset < 0 ? 0 : newOffset,
+ },
+ },
+ }));
+ };
const handlePreviousPagination = (): void => {
- if (isOrderByTimeStamp) {
- setRequestData((prev) => ({
- ...prev,
- query: {
- ...prev.query,
- builder: {
- ...prev.query.builder,
- queryData: [
- {
- ...prev.query.builder.queryData[0],
- filters: {
- ...prev.query.builder.queryData[0].filters,
- items: [
- ...getNextOrPreviousItems(
- prev.query.builder.queryData[0].filters.items,
- 'PREV',
- firstLog,
- ),
- ],
- },
- limit: 0,
- offset: 0,
- },
- ],
- },
- },
- }));
- }
- if (!isOrderByTimeStamp) {
- setPagination({
- ...pagination,
- limit: 0,
- offset: pagination.offset - pageSize,
- });
- }
+ const newOffset = offset - pageSize;
+ handleRequestData(newOffset);
};
const handleNextPagination = (): void => {
- if (isOrderByTimeStamp) {
- setRequestData((prev) => ({
- ...prev,
- query: {
- ...prev.query,
- builder: {
- ...prev.query.builder,
- queryData: [
- {
- ...prev.query.builder.queryData[0],
- filters: {
- ...prev.query.builder.queryData[0].filters,
- items: [
- ...getNextOrPreviousItems(
- prev.query.builder.queryData[0].filters.items,
- 'NEXT',
- lastLog,
- ),
- ],
- },
- limit: 0,
- offset: 0,
- },
- ],
- },
- },
- }));
- }
- if (!isOrderByTimeStamp) {
- setPagination({
- ...pagination,
- limit: 0,
- offset: pagination.offset + pageSize,
- });
- }
+ const newOffset = offset + pageSize;
+ handleRequestData(newOffset);
};
if (queryResponse.isError) {
@@ -231,6 +144,7 @@ function LogsPanelComponent({
dataSource={flattenLogData}
columns={columns}
onRow={handleRow}
+ rowKey={(record): string => record.id}
widgetId={widget.id}
shouldPersistColumnWidths
/>
@@ -242,12 +156,11 @@ function LogsPanelComponent({
totalCount={totalCount}
perPageOptions={PER_PAGE_OPTIONS}
isLoading={queryResponse.isFetching}
- offset={pagination.offset}
+ offset={offset}
countPerPage={pageSize}
handleNavigatePrevious={handlePreviousPagination}
handleNavigateNext={handleNextPagination}
handleCountItemsPerPageChange={handleChangePageSize}
- isLogPanel={isOrderByTimeStamp}
/>
</div>
)}
diff --git a/frontend/src/container/LogsPanelTable/__tests__/LogsPanelComponent.test.tsx b/frontend/src/container/LogsPanelTable/__tests__/LogsPanelComponent.test.tsx
new file mode 100644
index 0000000000..d77f05f1bd
--- /dev/null
+++ b/frontend/src/container/LogsPanelTable/__tests__/LogsPanelComponent.test.tsx
@@ -0,0 +1,189 @@
+import { ENVIRONMENT } from 'constants/env';
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import NewWidget from 'container/NewWidget';
+import { logsPaginationQueryRangeSuccessResponse } from 'mocks-server/__mockdata__/logs_query_range';
+import { server } from 'mocks-server/server';
+import { rest } from 'msw';
+import { DashboardProvider } from 'providers/Dashboard/Dashboard';
+import { I18nextProvider } from 'react-i18next';
+import i18n from 'ReactI18';
+import { act, fireEvent, render, screen, waitFor } from 'tests/test-utils';
+import { QueryRangePayload } from 'types/api/metrics/getQueryRange';
+import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+
+// Constants
+const QUERY_RANGE_URL = `${ENVIRONMENT.baseURL}/api/v3/query_range`;
+const MOCK_SEARCH_PARAMS =
+ '?graphType=list&widgetId=36a7b342-c642-4b92-abe4-cb833a244786&compositeQuery=%7B%22id%22%3A%22b325ac88-5e75-4117-a38c-1a2a7caf8115%22%2C%22builder%22%3A%7B%22queryData%22%3A%5B%7B%22dataSource%22%3A%22logs%22%2C%22queryName%22%3A%22A%22%2C%22aggregateOperator%22%3A%22noop%22%2C%22aggregateAttribute%22%3A%7B%22id%22%3A%22------%22%2C%22dataType%22%3A%22%22%2C%22key%22%3A%22%22%2C%22isColumn%22%3Afalse%2C%22type%22%3A%22%22%2C%22isJSON%22%3Afalse%7D%2C%22timeAggregation%22%3A%22rate%22%2C%22spaceAggregation%22%3A%22sum%22%2C%22functions%22%3A%5B%5D%2C%22filters%22%3A%7B%22items%22%3A%5B%5D%2C%22op%22%3A%22AND%22%7D%2C%22expression%22%3A%22A%22%2C%22disabled%22%3Afalse%2C%22stepInterval%22%3A60%2C%22having%22%3A%5B%5D%2C%22limit%22%3Anull%2C%22orderBy%22%3A%5B%7B%22columnName%22%3A%22timestamp%22%2C%22order%22%3A%22desc%22%7D%5D%2C%22groupBy%22%3A%5B%5D%2C%22legend%22%3A%22%22%2C%22reduceTo%22%3A%22avg%22%2C%22offset%22%3A0%2C%22pageSize%22%3A100%7D%5D%2C%22queryFormulas%22%3A%5B%5D%7D%2C%22clickhouse_sql%22%3A%5B%7B%22name%22%3A%22A%22%2C%22legend%22%3A%22%22%2C%22disabled%22%3Afalse%2C%22query%22%3A%22%22%7D%5D%2C%22promql%22%3A%5B%7B%22name%22%3A%22A%22%2C%22query%22%3A%22%22%2C%22legend%22%3A%22%22%2C%22disabled%22%3Afalse%7D%5D%2C%22queryType%22%3A%22builder%22%7D&relativeTime=30m&options=%7B%22selectColumns%22%3A%5B%5D%2C%22maxLines%22%3A2%2C%22format%22%3A%22list%22%2C%22fontSize%22%3A%22small%22%7D';
+
+// Mocks
+jest.mock('uplot', () => ({
+ paths: { spline: jest.fn(), bars: jest.fn() },
+ default: jest.fn(() => ({ paths: { spline: jest.fn(), bars: jest.fn() } })),
+}));
+
+jest.mock('components/OverlayScrollbar/OverlayScrollbar', () => ({
+ __esModule: true,
+ default: ({ children }: { children: React.ReactNode }): JSX.Element => (
+ <div>{children}</div>
+ ),
+}));
+
+jest.mock('react-router-dom', () => ({
+ ...jest.requireActual('react-router-dom'),
+ useLocation: (): { pathname: string; search: string } => ({
+ pathname: '',
+ search: MOCK_SEARCH_PARAMS,
+ }),
+}));
+
+jest.mock('hooks/useSafeNavigate', () => ({
+ useSafeNavigate: (): { safeNavigate: jest.Mock } => ({
+ safeNavigate: jest.fn(),
+ }),
+}));
+
+jest.mock('container/TopNav/DateTimeSelectionV2/index.tsx', () => ({
+ __esModule: true,
+ default: (): JSX.Element => <div>MockDateTimeSelection</div>,
+}));
+
+// Helpers
+const getBuilderQuery = (payload: QueryRangePayload): IBuilderQuery =>
+ payload.compositeQuery.builderQueries?.A as IBuilderQuery;
+
+const assertTimeRangeConsistency = (
+ payload: QueryRangePayload,
+ initialTimeRange: { start: number; end: number },
+): void => {
+ expect(payload.start).toBe(initialTimeRange.start);
+ expect(payload.end).toBe(initialTimeRange.end);
+};
+
+jest.mock('container/QueryBuilder', () => ({
+ QueryBuilder: function MockQuerySection(): JSX.Element {
+ return <div>MockQuerySection</div>;
+ },
+}));
+
+jest.setTimeout(20000);
+
+Object.defineProperty(globalThis, 'matchMedia', {
+ writable: true,
+ value: jest.fn().mockImplementation((query) => ({
+ matches: true,
+ media: query,
+ addListener: (listener: (params: { matches: boolean }) => void): void => {
+ listener({ matches: true });
+ },
+ removeListener: jest.fn(),
+ })),
+});
+
+describe('LogsPanelComponent', () => {
+ let capturedQueryRangePayloads: QueryRangePayload[] = [];
+
+ beforeEach(() => {
+ capturedQueryRangePayloads = [];
+ server.use(
+ rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
+ const payload = await req.json();
+ capturedQueryRangePayloads.push(payload);
+
+ const queryData = getBuilderQuery(payload);
+ return res(
+ ctx.status(200),
+ ctx.json(
+ logsPaginationQueryRangeSuccessResponse({
+ offset: queryData?.offset ?? 0,
+ pageSize: 10,
+ }),
+ ),
+ );
+ }),
+ );
+ });
+
+ const renderComponent = async (): Promise<void> => {
+ render(
+ <I18nextProvider i18n={i18n}>
+ <DashboardProvider>
+ <NewWidget
+ selectedGraph={PANEL_TYPES.LIST}
+ fillSpans={undefined}
+ yAxisUnit={undefined}
+ />
+ </DashboardProvider>
+ </I18nextProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.queryByText('No data')).not.toBeInTheDocument();
+ });
+ };
+
+ it('should handle pagination flows correctly', async () => {
+ await renderComponent();
+ const initialTimeRange = {
+ start: capturedQueryRangePayloads[0].start,
+ end: capturedQueryRangePayloads[0].end,
+ };
+
+ act(() => {
+ fireEvent.click(screen.getByRole('button', { name: /next/i }));
+ });
+ await waitFor(() => {
+ expect(capturedQueryRangePayloads).toHaveLength(2);
+ });
+
+ const firstPayload = capturedQueryRangePayloads[0];
+ const secondPayload = capturedQueryRangePayloads[1];
+
+ const firstQueryData = getBuilderQuery(firstPayload);
+ const secondQueryData = getBuilderQuery(secondPayload);
+
+ expect(firstQueryData.offset).toBe(0);
+ expect(secondQueryData.offset).toBe(10);
+ assertTimeRangeConsistency(secondPayload, initialTimeRange);
+ const idFilter = secondQueryData.filters?.items?.find(
+ (item) => item?.key?.key === 'id',
+ );
+ expect(idFilter).toBeUndefined();
+
+ const secondOrderByTimestamp = secondQueryData.orderBy?.find(
+ (item) => item.columnName === 'timestamp',
+ );
+ const secondOrderById = secondQueryData.orderBy?.find(
+ (item) => item.columnName === 'id',
+ );
+ expect(secondOrderByTimestamp).toBeDefined();
+ expect(secondOrderById).toBeDefined();
+ expect(secondOrderById?.order).toBe(secondOrderByTimestamp?.order);
+
+ act(() => {
+ fireEvent.click(screen.getByRole('button', { name: /previous/i }));
+ });
+ await waitFor(() => {
+ expect(capturedQueryRangePayloads).toHaveLength(3);
+ });
+
+ const thirdPayload = capturedQueryRangePayloads[2];
+ const thirdQueryData = getBuilderQuery(thirdPayload);
+ expect(thirdQueryData.offset).toBe(0);
+ assertTimeRangeConsistency(thirdPayload, initialTimeRange);
+ const thirdIdFilter = thirdQueryData.filters?.items?.find(
+ (item) => item?.key?.key === 'id',
+ );
+ expect(thirdIdFilter).toBeUndefined();
+
+ const thirdOrderByTimestamp = thirdQueryData.orderBy?.find(
+ (item) => item.columnName === 'timestamp',
+ );
+ const thirdOrderById = thirdQueryData.orderBy?.find(
+ (item) => item.columnName === 'id',
+ );
+ expect(thirdOrderByTimestamp).toBeDefined();
+ expect(thirdOrderById).toBeDefined();
+ expect(thirdOrderById?.order).toBe(thirdOrderByTimestamp?.order);
+ });
+});
diff --git a/frontend/src/container/LogsPanelTable/utils.tsx b/frontend/src/container/LogsPanelTable/utils.tsx
index 954526bde1..34bce54e24 100644
--- a/frontend/src/container/LogsPanelTable/utils.tsx
+++ b/frontend/src/container/LogsPanelTable/utils.tsx
@@ -1,16 +1,11 @@
import { ColumnsType } from 'antd/es/table';
import { Typography } from 'antd/lib';
-import { OPERATORS } from 'constants/queryBuilder';
import { TimestampInput } from 'hooks/useTimezoneFormatter/useTimezoneFormatter';
// import Typography from 'antd/es/typography/Typography';
import { RowData } from 'lib/query/createTableColumnsFromQuery';
import { ReactNode } from 'react';
import { Widgets } from 'types/api/dashboard/getAll';
import { IField } from 'types/api/logs/fields';
-import { ILog } from 'types/api/logs/log';
-import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
-import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
-import { v4 as uuid } from 'uuid';
export const getLogPanelColumnsList = (
selectedLogFields: Widgets['selectedLogFields'],
@@ -55,49 +50,3 @@ export const getLogPanelColumnsList = (
return [...initialColumns, ...columns];
};
-
-export const getNextOrPreviousItems = (
- items: TagFilterItem[],
- direction: 'NEXT' | 'PREV',
- log?: ILog,
-): TagFilterItem[] => {
- const nextItem = {
- id: uuid(),
- key: {
- key: 'id',
- type: '',
- dataType: DataTypes.String,
- isColumn: true,
- },
- op: OPERATORS['<'],
- value: log?.id || '',
- };
- const prevItem = {
- id: uuid(),
- key: {
- key: 'id',
- type: '',
- dataType: DataTypes.String,
- isColumn: true,
- },
- op: OPERATORS['>'],
- value: log?.id || '',
- };
- let index = items.findIndex((item) => item.op === OPERATORS['<']);
- if (index === -1) {
- index = items.findIndex((item) => item.op === OPERATORS['>']);
- }
- if (index === -1) {
- if (direction === 'NEXT') {
- return [...items, nextItem];
- }
- return [...items, prevItem];
- }
- const newItems = [...items];
- if (direction === 'NEXT') {
- newItems[index] = nextItem;
- } else {
- newItems[index] = prevItem;
- }
- return newItems;
-};
diff --git a/frontend/src/container/NewWidget/index.tsx b/frontend/src/container/NewWidget/index.tsx
index dc8eafe76c..9c4c809971 100644
--- a/frontend/src/container/NewWidget/index.tsx
+++ b/frontend/src/container/NewWidget/index.tsx
@@ -97,6 +97,19 @@ function NewWidget({ selectedGraph }: NewWidgetProps): JSX.Element {
GlobalReducer
>((state) => state.globalTime);
+ const isLogsQuery = currentQuery.builder.queryData.every(
+ (query) => query.dataSource === DataSource.LOGS,
+ );
+
+ const customGlobalSelectedInterval = useMemo(
+ () =>
+ // custom selected time interval for list panel to prevent recalculating the start and end timestamps before fetching next / prev pages
+ selectedGraph === PANEL_TYPES.LIST && isLogsQuery
+ ? 'custom'
+ : globalSelectedInterval,
+ [selectedGraph, globalSelectedInterval, isLogsQuery],
+ );
+
const { widgets = [] } = selectedDashboard?.data || {};
const query = useUrlQuery();
@@ -329,7 +342,7 @@ function NewWidget({ selectedGraph }: NewWidgetProps): JSX.Element {
query: updatedQuery,
graphType: PANEL_TYPES.LIST,
selectedTime: selectedTime.enum || 'GLOBAL_TIME',
- globalSelectedInterval,
+ globalSelectedInterval: customGlobalSelectedInterval,
variables: getDashboardVariables(selectedDashboard?.data.variables),
tableParams: {
pagination: {
@@ -343,7 +356,7 @@ function NewWidget({ selectedGraph }: NewWidgetProps): JSX.Element {
selectedTime: selectedWidget?.timePreferance,
graphType: getGraphType(selectedGraph || selectedWidget.panelTypes),
query: stagedQuery || initialQueriesMap.metrics,
- globalSelectedInterval,
+ globalSelectedInterval: customGlobalSelectedInterval,
formatForWeb:
getGraphTypeForFormat(selectedGraph || selectedWidget.panelTypes) ===
PANEL_TYPES.TABLE,
@@ -359,7 +372,7 @@ function NewWidget({ selectedGraph }: NewWidgetProps): JSX.Element {
query: updatedQuery,
graphType: selectedGraph,
selectedTime: selectedTime.enum || 'GLOBAL_TIME',
- globalSelectedInterval,
+ globalSelectedInterval: customGlobalSelectedInterval,
variables: getDashboardVariables(selectedDashboard?.data.variables),
};
});
@@ -367,12 +380,14 @@ function NewWidget({ selectedGraph }: NewWidgetProps): JSX.Element {
useEffect(() => {
if (stagedQuery) {
setIsLoadingPanelData(false);
+ const updatedStagedQuery = cloneDeep(stagedQuery);
+ updatedStagedQuery.builder.queryData[0].pageSize = 10;
setRequestData((prev) => ({
...prev,
selectedTime: selectedTime.enum || prev.selectedTime,
- globalSelectedInterval,
+ globalSelectedInterval: customGlobalSelectedInterval,
graphType: getGraphType(selectedGraph || selectedWidget.panelTypes),
- query: stagedQuery,
+ query: updatedStagedQuery,
fillGaps: selectedWidget.fillSpans || false,
isLogScale: selectedWidget.isLogScale || false,
formatForWeb:
diff --git a/frontend/src/hooks/infraMonitoring/useHandleLogsPagination.tsx b/frontend/src/hooks/infraMonitoring/useHandleLogsPagination.tsx
new file mode 100644
index 0000000000..ccf88985eb
--- /dev/null
+++ b/frontend/src/hooks/infraMonitoring/useHandleLogsPagination.tsx
@@ -0,0 +1,181 @@
+import { DEFAULT_PER_PAGE_VALUE } from 'container/Controls/config';
+import { ORDERBY_FILTERS } from 'container/QueryBuilder/filters/OrderByFilter/config';
+import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
+import { isEqual } from 'lodash-es';
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from 'react';
+import { ILog } from 'types/api/logs/log';
+import {
+ IBuilderQuery,
+ TagFilterItem,
+} from 'types/api/queryBuilder/queryBuilderData';
+
+interface TimeRange {
+ startTime: number;
+ endTime: number;
+}
+
+interface UsePaginatedLogsProps {
+ timeRange: TimeRange;
+ filters: IBuilderQuery['filters'];
+ queryKeyFilters?: string[];
+ excludeFilterKeys?: string[];
+ basePayload: GetQueryResultsProps;
+}
+
+interface UseHandleLogsPagination {
+ logs: ILog[];
+ hasReachedEndOfLogs: boolean;
+ isPaginating: boolean;
+ currentPage: number;
+ resetLogsList: boolean;
+ setIsPaginating: Dispatch<SetStateAction<boolean>>;
+ handleNewData: (currentData: any) => void;
+ loadMoreLogs: () => void;
+ shouldResetPage: boolean;
+ queryPayload: GetQueryResultsProps;
+}
+
+export const useHandleLogsPagination = ({
+ timeRange,
+ filters,
+ queryKeyFilters = [],
+ excludeFilterKeys = [],
+ basePayload,
+}: UsePaginatedLogsProps): UseHandleLogsPagination => {
+ const [logs, setLogs] = useState<ILog[]>([]);
+ const [hasReachedEndOfLogs, setHasReachedEndOfLogs] = useState(false);
+ const [restFilters, setRestFilters] = useState<TagFilterItem[]>([]);
+ const [resetLogsList, setResetLogsList] = useState<boolean>(false);
+ const [page, setPage] = useState(1);
+ const [prevTimeRange, setPrevTimeRange] = useState<TimeRange | null>(
+ timeRange,
+ );
+ const [isPaginating, setIsPaginating] = useState(false);
+
+ const { shouldResetPage, newRestFilters } = useMemo(() => {
+ const newRestFilters = filters.items.filter((item) => {
+ const keyToCheck = item.key?.key ?? '';
+ return (
+ !queryKeyFilters.includes(keyToCheck) &&
+ !excludeFilterKeys.includes(keyToCheck)
+ );
+ });
+
+ const areFiltersSame = isEqual(restFilters, newRestFilters);
+
+ const shouldResetPage =
+ !areFiltersSame ||
+ timeRange.startTime !== prevTimeRange?.startTime ||
+ timeRange.endTime !== prevTimeRange?.endTime;
+
+ return { shouldResetPage, newRestFilters };
+ }, [
+ filters,
+ timeRange,
+ prevTimeRange,
+ queryKeyFilters,
+ excludeFilterKeys,
+ restFilters,
+ ]);
+
+ const currentPage = useMemo(() => {
+ if (shouldResetPage) {
+ return 1;
+ }
+ return page;
+ }, [shouldResetPage, page]);
+
+ // Handle data updates
+ const handleNewData = useCallback(
+ (currentData: any) => {
+ if (!currentData[0].list) {
+ setHasReachedEndOfLogs(true);
+ return;
+ }
+
+ const currentLogs: ILog[] =
+ currentData[0].list?.map((item: any) => ({
+ ...item.data,
+ timestamp: item.timestamp,
+ })) || [];
+
+ if (resetLogsList) {
+ setLogs(currentLogs);
+ setResetLogsList(false);
+ return;
+ }
+
+ const newLogs = currentLogs.filter(
+ (newLog) => !logs.some((existingLog) => isEqual(existingLog, newLog)),
+ );
+
+ if (newLogs.length > 0) {
+ setLogs((prev) => [...prev, ...newLogs]);
+ }
+ },
+ [logs, resetLogsList],
+ );
+
+ // Reset logic
+ useEffect(() => {
+ if (shouldResetPage) {
+ setPage(1);
+ setLogs([]);
+ setResetLogsList(true);
+ }
+
+ setPrevTimeRange(timeRange);
+ setRestFilters(newRestFilters);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [shouldResetPage, timeRange]);
+
+ const loadMoreLogs = useCallback(() => {
+ if (!logs.length) return;
+ setPage((prev) => prev + 1);
+ setIsPaginating(true);
+ }, [logs]);
+
+ const queryPayload = useMemo(
+ () => ({
+ ...basePayload,
+ query: {
+ ...basePayload.query,
+ builder: {
+ ...basePayload.query.builder,
+ queryData: [
+ {
+ ...basePayload.query.builder.queryData[0],
+ pageSize: DEFAULT_PER_PAGE_VALUE,
+ offset: (currentPage - 1) * DEFAULT_PER_PAGE_VALUE,
+ orderBy: [
+ { columnName: 'timestamp', order: ORDERBY_FILTERS.DESC },
+ { columnName: 'id', order: ORDERBY_FILTERS.DESC },
+ ],
+ },
+ ],
+ },
+ },
+ }),
+ [basePayload, currentPage],
+ );
+
+ return {
+ logs,
+ hasReachedEndOfLogs,
+ isPaginating,
+ currentPage,
+ resetLogsList,
+ queryPayload,
+ setIsPaginating,
+ handleNewData,
+ loadMoreLogs,
+ shouldResetPage,
+ };
+};
diff --git a/frontend/src/hooks/queryBuilder/useGetExplorerQueryRange.ts b/frontend/src/hooks/queryBuilder/useGetExplorerQueryRange.ts
index 13093ab254..a81e7ccfc7 100644
--- a/frontend/src/hooks/queryBuilder/useGetExplorerQueryRange.ts
+++ b/frontend/src/hooks/queryBuilder/useGetExplorerQueryRange.ts
@@ -1,5 +1,6 @@
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
+import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { MutableRefObject, useMemo } from 'react';
import { UseQueryOptions, UseQueryResult } from 'react-query';
import { useSelector } from 'react-redux';
@@ -21,6 +22,7 @@ export const useGetExplorerQueryRange = (
isDependentOnQB = true,
keyRef?: MutableRefObject<any>,
headers?: Record<string, string>,
+ selectedTimeInterval?: GetQueryResultsProps['globalSelectedInterval'],
): UseQueryResult<SuccessResponse<MetricRangePayloadProps>, Error> => {
const { isEnabledQuery } = useQueryBuilder();
const { selectedTime: globalSelectedInterval, minTime, maxTime } = useSelector<
@@ -51,7 +53,8 @@ export const useGetExplorerQueryRange = (
{
graphType: panelType || PANEL_TYPES.LIST,
selectedTime: 'GLOBAL_TIME',
- globalSelectedInterval,
+ globalSelectedInterval: selectedTimeInterval ?? globalSelectedInterval,
+
query: requestData || initialQueriesMap.metrics,
params,
},
@@ -59,7 +62,13 @@ export const useGetExplorerQueryRange = (
{
...options,
retry: false,
- queryKey: [key, globalSelectedInterval, requestData, minTime, maxTime],
+ queryKey: [
+ key,
+ selectedTimeInterval ?? globalSelectedInterval,
+ requestData,
+ minTime,
+ maxTime,
+ ],
enabled: isEnabled,
},
headers,
diff --git a/frontend/src/hooks/queryBuilder/useGetQueryRange.ts b/frontend/src/hooks/queryBuilder/useGetQueryRange.ts
index e0c6ea3172..172c5c0580 100644
--- a/frontend/src/hooks/queryBuilder/useGetQueryRange.ts
+++ b/frontend/src/hooks/queryBuilder/useGetQueryRange.ts
@@ -22,16 +22,46 @@ export const useGetQueryRange: UseGetQueryRange = (
options,
headers,
) => {
- const newRequestData: GetQueryResultsProps = useMemo(
- () => ({
+ const newRequestData: GetQueryResultsProps = useMemo(() => {
+ const isListWithSingleTimestampOrder =
+ requestData.graphType === PANEL_TYPES.LIST &&
+ requestData.query.builder?.queryData[0]?.orderBy?.length === 1 &&
+ // exclude list with id filter (i.e. context logs)
+ !requestData.query.builder?.queryData[0].filters.items.some(
+ (filter) => filter.key?.key === 'id',
+ ) &&
+ requestData.query.builder?.queryData[0].orderBy[0].columnName ===
+ 'timestamp';
+
+ const modifiedRequestData = {
...requestData,
graphType:
requestData.graphType === PANEL_TYPES.BAR
? PANEL_TYPES.TIME_SERIES
: requestData.graphType,
- }),
- [requestData],
- );
+ };
+
+ // If the query is a list with a single timestamp order, we need to add the id column to the order by clause
+ if (isListWithSingleTimestampOrder) {
+ modifiedRequestData.query.builder = {
+ ...requestData.query.builder,
+ queryData: [
+ {
+ ...requestData.query.builder.queryData[0],
+ orderBy: [
+ ...requestData.query.builder.queryData[0].orderBy,
+ {
+ columnName: 'id',
+ order: requestData.query.builder.queryData[0].orderBy[0].order,
+ },
+ ],
+ },
+ ],
+ };
+ }
+
+ return modifiedRequestData;
+ }, [requestData]);
const queryKey = useMemo(() => {
if (options?.queryKey && Array.isArray(options.queryKey)) {
diff --git a/frontend/src/hooks/useLogsData.ts b/frontend/src/hooks/useLogsData.ts
index 2f29fcd17b..86a3f07034 100644
--- a/frontend/src/hooks/useLogsData.ts
+++ b/frontend/src/hooks/useLogsData.ts
@@ -5,7 +5,7 @@ import {
PANEL_TYPES,
} from 'constants/queryBuilder';
import { DEFAULT_PER_PAGE_VALUE } from 'container/Controls/config';
-import { getPaginationQueryData } from 'lib/newQueryBuilder/getPaginationQueryData';
+import { getPaginationQueryDataV2 } from 'lib/newQueryBuilder/getPaginationQueryData';
import { useEffect, useMemo, useState } from 'react';
import { useSelector } from 'react-redux';
import { AppState } from 'store/reducers';
@@ -99,10 +99,7 @@ export const useLogsData = ({
): Query | null => {
if (!query) return null;
- const paginateData = getPaginationQueryData({
- filters: params.filters,
- listItemId: params.log ? params.log.id : null,
- orderByTimestamp,
+ const paginateData = getPaginationQueryDataV2({
page: params.page,
pageSize: params.pageSize,
});
diff --git a/frontend/src/hooks/useResourceAttribute/machine.ts b/frontend/src/hooks/useResourceAttribute/machine.ts
index 7d7fa662a1..d295ba7080 100644
--- a/frontend/src/hooks/useResourceAttribute/machine.ts
+++ b/frontend/src/hooks/useResourceAttribute/machine.ts
@@ -57,5 +57,6 @@ export const ResourceAttributesFilterMachine =
},
},
},
+ predictableActionArguments: true,
id: 'ResourceAttributesFilterMachine',
});
diff --git a/frontend/src/lib/dashboard/prepareQueryRangePayload.ts b/frontend/src/lib/dashboard/prepareQueryRangePayload.ts
index 4999726c63..46eedebe6f 100644
--- a/frontend/src/lib/dashboard/prepareQueryRangePayload.ts
+++ b/frontend/src/lib/dashboard/prepareQueryRangePayload.ts
@@ -1,7 +1,6 @@
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
import getStep from 'lib/getStep';
import { mapQueryDataToApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi';
-import { isUndefined } from 'lodash-es';
import store from 'store';
import { QueryRangePayload } from 'types/api/metrics/getQueryRange';
import { EQueryType } from 'types/common/dashboard';
@@ -27,11 +26,7 @@ export const prepareQueryRangePayload = ({
end: endTime,
}: GetQueryResultsProps): PrepareQueryRangePayload => {
let legendMap: Record<string, string> = {};
- const {
- allowSelectedIntervalForStepGen,
- lastLogLineTimestamp,
- ...restParams
- } = params;
+ const { allowSelectedIntervalForStepGen, ...restParams } = params;
const compositeQuery: QueryRangePayload['compositeQuery'] = {
queryType: query.queryType,
@@ -97,13 +92,9 @@ export const prepareQueryRangePayload = ({
interval: globalSelectedInterval,
});
- const endLogTimeStamp = !isUndefined(lastLogLineTimestamp)
- ? new Date(lastLogLineTimestamp as string | number)?.getTime() || undefined
- : undefined;
-
const queryPayload: QueryRangePayload = {
start: startTime ? startTime * 1e3 : parseInt(start, 10) * 1e3,
- end: endTime ? endTime * 1e3 : endLogTimeStamp || parseInt(end, 10) * 1e3,
+ end: endTime ? endTime * 1e3 : parseInt(end, 10) * 1e3,
step: getStep({
start: allowSelectedIntervalForStepGen
? start
diff --git a/frontend/src/lib/newQueryBuilder/getPaginationQueryData.ts b/frontend/src/lib/newQueryBuilder/getPaginationQueryData.ts
index 1b6b0056d1..ea9450e47e 100644
--- a/frontend/src/lib/newQueryBuilder/getPaginationQueryData.ts
+++ b/frontend/src/lib/newQueryBuilder/getPaginationQueryData.ts
@@ -8,6 +8,27 @@ import {
} from 'types/api/queryBuilder/queryBuilderData';
import { v4 as uuid } from 'uuid';
+type SetupPaginationQueryDataParamsV2 = {
+ page: number;
+ pageSize: number;
+};
+
+type SetupPaginationQueryDataV2 = (
+ params: SetupPaginationQueryDataParamsV2,
+) => Partial<IBuilderQuery>;
+
+export const getPaginationQueryDataV2: SetupPaginationQueryDataV2 = ({
+ page,
+ pageSize,
+}) => {
+ const offset = (page - 1) * pageSize;
+
+ return {
+ offset,
+ pageSize,
+ };
+};
+
type SetupPaginationQueryDataParams = {
filters: IBuilderQuery['filters'];
listItemId: string | null;
diff --git a/frontend/src/mocks-server/__mockdata__/logs_query_range.ts b/frontend/src/mocks-server/__mockdata__/logs_query_range.ts
index 345e4e90a1..f2838c8216 100644
--- a/frontend/src/mocks-server/__mockdata__/logs_query_range.ts
+++ b/frontend/src/mocks-server/__mockdata__/logs_query_range.ts
@@ -1,3 +1,6 @@
+// Define a standard page size
+export const PAGE_SIZE = 100;
+
export const logsQueryRangeSuccessResponse = {
status: 'success',
data: {
@@ -43,3 +46,79 @@ export const logsQueryRangeSuccessResponse = {
],
},
};
+
+export const logsPaginationQueryRangeSuccessResponse = ({
+ offset = 0,
+ pageSize = PAGE_SIZE,
+}: {
+ offset?: number;
+ pageSize?: number;
+}): any => {
+ // Calculate the starting index for this page's items
+ const startIndex = offset;
+ // Determine how many items to generate for *this specific page*
+ // In a real scenario, this might be less than PAGE_SIZE if it's the last page
+ const itemsForThisPage = pageSize;
+
+ return {
+ status: 'success',
+ data: {
+ resultType: '',
+ result: [
+ {
+ queryName: 'A',
+ series: null,
+ // Generate only the items for the current page
+ list: Array.from({ length: itemsForThisPage }, (_, index) => {
+ // Calculate a unique index based on the overall position
+ const cumulativeIndex = startIndex + index;
+ const baseTimestamp = new Date('2024-02-15T21:20:22Z').getTime();
+ // Ensure timestamps decrease for descending order
+ const currentTimestamp = new Date(baseTimestamp - cumulativeIndex * 1000);
+ const timestampString = currentTimestamp.toISOString();
+ // Generate unique IDs based on the cumulative index
+ const id = `id-${cumulativeIndex}`; // Make ID unique across all pages
+ const spanId = `span_id_${cumulativeIndex}`;
+ const traceId = `trace_id_${cumulativeIndex}`;
+ const logLevel = ['INFO', 'WARN', 'ERROR'][cumulativeIndex % 3];
+ const service = ['frontend', 'backend', 'database'][cumulativeIndex % 3];
+ const containerName = `container_name_${cumulativeIndex % 10}`;
+
+ return {
+ timestamp: timestampString,
+ data: {
+ attributes_bool: {},
+ attributes_float64: {},
+ attributes_int64: {},
+ attributes_string: {
+ container_id: `container_id_${cumulativeIndex % 10}`,
+ container_name: containerName,
+ driver: 'driver',
+ eta: `${cumulativeIndex % 5}m${cumulativeIndex % 60}s`,
+ location: service,
+ log_level: logLevel,
+ message: `Log message for item ${cumulativeIndex}`,
+ service,
+ span_id: spanId,
+ trace_id: traceId,
+ },
+ body: `${timestampString} ${logLevel} ${service} Log message for item ${cumulativeIndex} {"service": "${service}", "trace_id": "${traceId}", "span_id": "${spanId}", "driver": "driver", "eta": "${
+ cumulativeIndex % 5
+ }m${cumulativeIndex % 60}s"}`,
+ id,
+ resources_string: {
+ 'container.name': containerName,
+ },
+ severity_number: [9, 13, 17][cumulativeIndex % 3],
+ severity_text: logLevel,
+ span_id: spanId,
+ trace_flags: 0,
+ trace_id: traceId,
+ },
+ };
+ }),
+ },
+ ],
+ },
+ };
+};
diff --git a/frontend/src/mocks-server/handlers.ts b/frontend/src/mocks-server/handlers.ts
index f0549025c1..ccb4dd603a 100644
--- a/frontend/src/mocks-server/handlers.ts
+++ b/frontend/src/mocks-server/handlers.ts
@@ -1,5 +1,7 @@
import { rest } from 'msw';
+import commonEnTranslation from '../../public/locales/en/common.json';
+import enTranslation from '../../public/locales/en/translation.json';
import { allAlertChannels } from './__mockdata__/alerts';
import { billingSuccessResponse } from './__mockdata__/billing';
import {
@@ -249,4 +251,16 @@ export const handlers = [
}),
),
),
+ rest.get('http://localhost/locales/en/translation.json', (_, res, ctx) =>
+ res(ctx.status(200), ctx.json(enTranslation)),
+ ),
+ rest.get('http://localhost/locales/en/common.json', (_, res, ctx) =>
+ res(ctx.status(200), ctx.json(commonEnTranslation)),
+ ),
+ rest.get('http://localhost/locales/en-US/translation.json', (_, res, ctx) =>
+ res(ctx.status(200), ctx.json(enTranslation)),
+ ),
+ rest.get('http://localhost/locales/en-US/common.json', (_, res, ctx) =>
+ res(ctx.status(200), ctx.json(commonEnTranslation)),
+ ),
];