mirror of
https://github.com/SigNoz/signoz.git
synced 2026-03-27 14:40:25 +00:00
Compare commits
7 Commits
main
...
fix/hosts-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2314c6ab6c | ||
|
|
64dab58fad | ||
|
|
d95a2264d6 | ||
|
|
a63e3408d6 | ||
|
|
558de5a950 | ||
|
|
7f9ad2ac0a | ||
|
|
3cc9ab6265 |
@@ -39,6 +39,7 @@ import {
|
||||
ScrollText,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { parseAsString, useQueryState } from 'nuqs';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import {
|
||||
@@ -52,15 +53,18 @@ import {
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { convertFiltersToExpression } from '../QueryBuilderV2/utils';
|
||||
import { VIEW_TYPES, VIEWS } from './constants';
|
||||
import Containers from './Containers/Containers';
|
||||
import { HostDetailProps } from './HostMetricDetail.interfaces';
|
||||
import HostMetricLogsDetailedView from './HostMetricsLogs/HostMetricLogsDetailedView';
|
||||
import { HOST_METRICS_LOGS_EXPR_QUERY_KEY } from './HostMetricsLogs/constants';
|
||||
import HostMetricsLogs from './HostMetricsLogs/HostMetricsLogs';
|
||||
import HostMetricTraces from './HostMetricTraces/HostMetricTraces';
|
||||
import Metrics from './Metrics/Metrics';
|
||||
import Processes from './Processes/Processes';
|
||||
|
||||
import './HostMetricsDetail.styles.scss';
|
||||
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
function HostMetricsDetails({
|
||||
host,
|
||||
@@ -129,10 +133,6 @@ function HostMetricsDetails({
|
||||
};
|
||||
}, [host?.hostName, searchParams]);
|
||||
|
||||
const [logFilters, setLogFilters] = useState<IBuilderQuery['filters']>(
|
||||
initialFilters,
|
||||
);
|
||||
|
||||
const [tracesFilters, setTracesFilters] = useState<IBuilderQuery['filters']>(
|
||||
initialFilters,
|
||||
);
|
||||
@@ -147,7 +147,6 @@ function HostMetricsDetails({
|
||||
}, [host]);
|
||||
|
||||
useEffect(() => {
|
||||
setLogFilters(initialFilters);
|
||||
setTracesFilters(initialFilters);
|
||||
}, [initialFilters]);
|
||||
|
||||
@@ -172,7 +171,6 @@ function HostMetricsDetails({
|
||||
setSearchParams({
|
||||
...Object.fromEntries(searchParams.entries()),
|
||||
[INFRA_MONITORING_K8S_PARAMS_KEYS.VIEW]: e.target.value,
|
||||
[INFRA_MONITORING_K8S_PARAMS_KEYS.LOG_FILTERS]: JSON.stringify(null),
|
||||
[INFRA_MONITORING_K8S_PARAMS_KEYS.TRACES_FILTERS]: JSON.stringify(null),
|
||||
});
|
||||
}
|
||||
@@ -210,48 +208,30 @@ function HostMetricsDetails({
|
||||
[],
|
||||
);
|
||||
|
||||
const handleChangeLogFilters = useCallback(
|
||||
(value: IBuilderQuery['filters'], view: VIEWS) => {
|
||||
setLogFilters((prevFilters) => {
|
||||
const hostNameFilter = prevFilters?.items?.find(
|
||||
(item) => item.key?.key === 'host.name',
|
||||
);
|
||||
const paginationFilter = value?.items?.find(
|
||||
(item) => item.key?.key === 'id',
|
||||
);
|
||||
const newFilters = value?.items?.filter(
|
||||
(item) => item.key?.key !== 'id' && item.key?.key !== 'host.name',
|
||||
);
|
||||
const initialLogsExpression = useMemo(
|
||||
() =>
|
||||
convertFiltersToExpression({
|
||||
items: [
|
||||
{
|
||||
id: uuidv4(),
|
||||
key: {
|
||||
key: 'host.name',
|
||||
dataType: DataTypes.String,
|
||||
type: 'resource',
|
||||
id: 'host.name--string--resource--false',
|
||||
},
|
||||
op: '=',
|
||||
value: host?.hostName || '',
|
||||
},
|
||||
],
|
||||
op: 'AND',
|
||||
}).expression,
|
||||
[host?.hostName],
|
||||
);
|
||||
|
||||
if (newFilters && newFilters?.length > 0) {
|
||||
logEvent(InfraMonitoringEvents.FilterApplied, {
|
||||
entity: InfraMonitoringEvents.HostEntity,
|
||||
view: InfraMonitoringEvents.LogsView,
|
||||
page: InfraMonitoringEvents.DetailedPage,
|
||||
});
|
||||
}
|
||||
|
||||
const updatedFilters = {
|
||||
op: 'AND',
|
||||
items: [
|
||||
hostNameFilter,
|
||||
...(newFilters || []),
|
||||
...(paginationFilter ? [paginationFilter] : []),
|
||||
].filter((item): item is TagFilterItem => item !== undefined),
|
||||
};
|
||||
|
||||
setSearchParams({
|
||||
...Object.fromEntries(searchParams.entries()),
|
||||
[INFRA_MONITORING_K8S_PARAMS_KEYS.LOG_FILTERS]: JSON.stringify(
|
||||
updatedFilters,
|
||||
),
|
||||
[INFRA_MONITORING_K8S_PARAMS_KEYS.VIEW]: view,
|
||||
});
|
||||
return updatedFilters;
|
||||
});
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[],
|
||||
const [hostMetricLogsExpr] = useQueryState(
|
||||
HOST_METRICS_LOGS_EXPR_QUERY_KEY,
|
||||
parseAsString,
|
||||
);
|
||||
|
||||
const handleChangeTracesFilters = useCallback(
|
||||
@@ -308,11 +288,6 @@ function HostMetricsDetails({
|
||||
});
|
||||
|
||||
if (selectedView === VIEW_TYPES.LOGS) {
|
||||
const filtersWithoutPagination = {
|
||||
...logFilters,
|
||||
items: logFilters?.items?.filter((item) => item.key?.key !== 'id') || [],
|
||||
};
|
||||
|
||||
const compositeQuery = {
|
||||
...initialQueryState,
|
||||
queryType: 'builder',
|
||||
@@ -322,7 +297,11 @@ function HostMetricsDetails({
|
||||
{
|
||||
...initialQueryBuilderFormValuesMap.logs,
|
||||
aggregateOperator: LogsAggregatorOperator.NOOP,
|
||||
filters: filtersWithoutPagination,
|
||||
filter: { expression: hostMetricLogsExpr },
|
||||
expression: hostMetricLogsExpr,
|
||||
having: {
|
||||
expression: '',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -564,12 +543,11 @@ function HostMetricsDetails({
|
||||
/>
|
||||
)}
|
||||
{selectedView === VIEW_TYPES.LOGS && (
|
||||
<HostMetricLogsDetailedView
|
||||
<HostMetricsLogs
|
||||
timeRange={modalTimeRange}
|
||||
isModalTimeSelection={isModalTimeSelection}
|
||||
handleTimeChange={handleTimeChange}
|
||||
handleChangeLogFilters={handleChangeLogFilters}
|
||||
logFilters={logFilters}
|
||||
initialExpression={initialLogsExpression}
|
||||
selectedInterval={selectedInterval}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
padding: var(--spacing-4) 0px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.logs {
|
||||
border: 1px solid var(--border);
|
||||
margin-top: var(--spacing-4);
|
||||
}
|
||||
|
||||
.listContainer {
|
||||
flex: 1;
|
||||
height: calc(100vh - 278px) !important;
|
||||
display: flex;
|
||||
height: 100%;
|
||||
|
||||
:global(.raw-log-content) {
|
||||
width: 100%;
|
||||
text-wrap: inherit;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
}
|
||||
|
||||
.listCard {
|
||||
width: 100%;
|
||||
margin-top: 12px;
|
||||
|
||||
:global(.ant-card-body) {
|
||||
padding: 0;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.logsLoadingSkeleton {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 8px 0;
|
||||
|
||||
:global(.ant-skeleton-input-sm) {
|
||||
height: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
.noLogsFound {
|
||||
height: 50vh;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
|
||||
p {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
.host-metrics-logs-container {
|
||||
margin-top: 1rem;
|
||||
|
||||
.filter-section {
|
||||
flex: 1;
|
||||
|
||||
.ant-select-selector {
|
||||
border-radius: 2px;
|
||||
border: 1px solid var(--bg-slate-400) !important;
|
||||
background-color: var(--bg-ink-300) !important;
|
||||
|
||||
input {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.ant-tag .ant-typography {
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.host-metrics-logs-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
|
||||
padding: 12px;
|
||||
border-radius: 3px;
|
||||
border: 1px solid var(--bg-slate-500);
|
||||
}
|
||||
|
||||
.host-metrics-logs {
|
||||
margin-top: 1rem;
|
||||
|
||||
.virtuoso-list {
|
||||
overflow-y: hidden !important;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 0.3rem;
|
||||
height: 0.3rem;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--bg-slate-300);
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--bg-slate-200);
|
||||
}
|
||||
|
||||
.ant-row {
|
||||
width: fit-content;
|
||||
}
|
||||
}
|
||||
|
||||
.skeleton-container {
|
||||
height: 100%;
|
||||
padding: 16px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.host-metrics-logs-list-container {
|
||||
flex: 1;
|
||||
height: calc(100vh - 272px) !important;
|
||||
display: flex;
|
||||
height: 100%;
|
||||
|
||||
.raw-log-content {
|
||||
width: 100%;
|
||||
text-wrap: inherit;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
}
|
||||
|
||||
.host-metrics-logs-list-card {
|
||||
width: 100%;
|
||||
margin-top: 12px;
|
||||
|
||||
.ant-card-body {
|
||||
padding: 0;
|
||||
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.logs-loading-skeleton {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 8px 0;
|
||||
|
||||
.ant-skeleton-input-sm {
|
||||
height: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
.no-logs-found {
|
||||
height: 50vh;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
|
||||
.ant-typography {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.lightMode {
|
||||
.filter-section {
|
||||
border-top: 1px solid var(--bg-vanilla-300);
|
||||
border-bottom: 1px solid var(--bg-vanilla-300);
|
||||
|
||||
.ant-select-selector {
|
||||
border-color: var(--bg-vanilla-300) !important;
|
||||
background-color: var(--bg-vanilla-100) !important;
|
||||
color: var(--bg-ink-200);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
import QueryBuilderSearch from 'container/QueryBuilder/filters/QueryBuilderSearch';
|
||||
import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
|
||||
import {
|
||||
CustomTimeType,
|
||||
Time,
|
||||
} from 'container/TopNav/DateTimeSelectionV2/types';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { VIEWS } from '../constants';
|
||||
import HostMetricsLogs from './HostMetricsLogs';
|
||||
|
||||
import './HostMetricLogs.styles.scss';
|
||||
|
||||
interface Props {
|
||||
timeRange: {
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
};
|
||||
isModalTimeSelection: boolean;
|
||||
handleTimeChange: (
|
||||
interval: Time | CustomTimeType,
|
||||
dateTimeRange?: [number, number],
|
||||
) => void;
|
||||
handleChangeLogFilters: (value: IBuilderQuery['filters'], view: VIEWS) => void;
|
||||
logFilters: IBuilderQuery['filters'];
|
||||
selectedInterval: Time;
|
||||
}
|
||||
|
||||
function HostMetricLogsDetailedView({
|
||||
timeRange,
|
||||
isModalTimeSelection,
|
||||
handleTimeChange,
|
||||
handleChangeLogFilters,
|
||||
logFilters,
|
||||
selectedInterval,
|
||||
}: Props): JSX.Element {
|
||||
const { currentQuery } = useQueryBuilder();
|
||||
const updatedCurrentQuery = useMemo(
|
||||
() => ({
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: [
|
||||
{
|
||||
...currentQuery.builder.queryData[0],
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregateOperator: 'noop',
|
||||
aggregateAttribute: {
|
||||
...currentQuery.builder.queryData[0].aggregateAttribute,
|
||||
},
|
||||
filters: {
|
||||
items:
|
||||
logFilters?.items?.filter((item) => item.key?.key !== 'host.name') ||
|
||||
[],
|
||||
op: 'AND',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
[currentQuery, logFilters?.items],
|
||||
);
|
||||
|
||||
const query = updatedCurrentQuery?.builder?.queryData[0] || null;
|
||||
|
||||
return (
|
||||
<div className="host-metrics-logs-container">
|
||||
<div className="host-metrics-logs-header">
|
||||
<div className="filter-section">
|
||||
{query && (
|
||||
<QueryBuilderSearch
|
||||
query={query as IBuilderQuery}
|
||||
onChange={(value): void => handleChangeLogFilters(value, VIEWS.LOGS)}
|
||||
disableNavigationShortcuts
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="datetime-section">
|
||||
<DateTimeSelectionV2
|
||||
showAutoRefresh
|
||||
showRefreshText={false}
|
||||
hideShareModal
|
||||
isModalTimeSelection={isModalTimeSelection}
|
||||
onTimeChange={handleTimeChange}
|
||||
defaultRelativeTime="5m"
|
||||
modalSelectedInterval={selectedInterval}
|
||||
modalInitialStartTime={timeRange.startTime * 1000}
|
||||
modalInitialEndTime={timeRange.endTime * 1000}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<HostMetricsLogs timeRange={timeRange} filters={logFilters} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default HostMetricLogsDetailedView;
|
||||
@@ -1,88 +1,161 @@
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
|
||||
import { Card } from 'antd';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import LogDetail from 'components/LogDetail';
|
||||
import RawLogView from 'components/Logs/RawLogView';
|
||||
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
|
||||
import { DEFAULT_ENTITY_VERSION } from 'constants/app';
|
||||
import QuerySearch from 'components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch';
|
||||
import { InfraMonitoringEvents } from 'constants/events';
|
||||
import LogsError from 'container/LogsError/LogsError';
|
||||
import { LogsLoading } from 'container/LogsLoading/LogsLoading';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { useHandleLogsPagination } from 'hooks/infraMonitoring/useHandleLogsPagination';
|
||||
import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
|
||||
import {
|
||||
CustomTimeType,
|
||||
Time,
|
||||
} from 'container/TopNav/DateTimeSelectionV2/types';
|
||||
import { getOldLogsOperatorFromNew } from 'hooks/logs/useActiveLog';
|
||||
import useLogDetailHandlers from 'hooks/logs/useLogDetailHandlers';
|
||||
import useScrollToLog from 'hooks/logs/useScrollToLog';
|
||||
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
|
||||
import useDebounce from 'hooks/useDebounce';
|
||||
import { generateFilterQuery } from 'lib/logs/generateFilterQuery';
|
||||
import { parseAsString, useQueryState } from 'nuqs';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { validateQuery } from 'utils/queryValidationUtils';
|
||||
|
||||
import { getHostLogsQueryPayload } from './constants';
|
||||
import {
|
||||
getHostLogsQueryPayload,
|
||||
HOST_METRICS_LOGS_EXPR_QUERY_KEY,
|
||||
} from './constants';
|
||||
import { useInfiniteHostMetricLogs } from './hooks';
|
||||
import NoLogsContainer from './NoLogsContainer';
|
||||
|
||||
import './HostMetricLogs.styles.scss';
|
||||
import styles from './HostMetricLogs.module.scss';
|
||||
|
||||
interface Props {
|
||||
initialExpression: string;
|
||||
timeRange: {
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
};
|
||||
filters: IBuilderQuery['filters'];
|
||||
isModalTimeSelection: boolean;
|
||||
handleTimeChange: (
|
||||
interval: Time | CustomTimeType,
|
||||
dateTimeRange?: [number, number],
|
||||
) => void;
|
||||
selectedInterval: Time;
|
||||
}
|
||||
|
||||
function HostMetricsLogs({ timeRange, filters }: Props): JSX.Element {
|
||||
const EXPRESSION_DEBOUNCE_TIME_MS = 300;
|
||||
|
||||
function HostMetricsLogs({
|
||||
initialExpression,
|
||||
timeRange,
|
||||
isModalTimeSelection,
|
||||
handleTimeChange,
|
||||
selectedInterval,
|
||||
}: Props): JSX.Element {
|
||||
const virtuosoRef = useRef<VirtuosoHandle>(null);
|
||||
|
||||
const [filterExpression, setFilterExpression] = useQueryState(
|
||||
HOST_METRICS_LOGS_EXPR_QUERY_KEY,
|
||||
parseAsString,
|
||||
);
|
||||
|
||||
const [inputExpression, setInputExpression] = useState(
|
||||
filterExpression || initialExpression,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// If expression is present in the URL, prefer it and don't override it.
|
||||
// Otherwise, initialize URL state from the host's default expression.
|
||||
if (filterExpression) {
|
||||
setInputExpression(filterExpression);
|
||||
return;
|
||||
}
|
||||
|
||||
setInputExpression(initialExpression);
|
||||
setFilterExpression(initialExpression);
|
||||
}, [filterExpression, initialExpression, setFilterExpression]);
|
||||
|
||||
const debouncedFilterExpression = useDebounce(
|
||||
filterExpression?.trim() || initialExpression,
|
||||
EXPRESSION_DEBOUNCE_TIME_MS,
|
||||
);
|
||||
|
||||
const {
|
||||
activeLog,
|
||||
onAddToQuery,
|
||||
selectedTab,
|
||||
handleSetActiveLog,
|
||||
handleCloseLogDetail,
|
||||
} = useLogDetailHandlers();
|
||||
|
||||
const basePayload = getHostLogsQueryPayload(
|
||||
timeRange.startTime,
|
||||
timeRange.endTime,
|
||||
filters,
|
||||
const onAddToQuery = useCallback(
|
||||
(fieldKey: string, fieldValue: string, operator: string): void => {
|
||||
handleCloseLogDetail();
|
||||
|
||||
const partExpression = generateFilterQuery({
|
||||
fieldKey,
|
||||
fieldValue,
|
||||
type: getOldLogsOperatorFromNew(operator),
|
||||
});
|
||||
|
||||
const newExpression = inputExpression.trim()
|
||||
? `${inputExpression} AND ${partExpression}`
|
||||
: partExpression;
|
||||
|
||||
setInputExpression(newExpression);
|
||||
setFilterExpression(newExpression);
|
||||
},
|
||||
[inputExpression, setFilterExpression, handleCloseLogDetail],
|
||||
);
|
||||
|
||||
const handleFilterChange = useCallback(
|
||||
(expression: string): void => {
|
||||
setInputExpression(expression);
|
||||
|
||||
const validation = validateQuery(expression);
|
||||
if (validation.isValid) {
|
||||
setFilterExpression(expression);
|
||||
|
||||
logEvent(InfraMonitoringEvents.FilterApplied, {
|
||||
entity: InfraMonitoringEvents.HostEntity,
|
||||
view: InfraMonitoringEvents.LogsView,
|
||||
page: InfraMonitoringEvents.DetailedPage,
|
||||
});
|
||||
}
|
||||
},
|
||||
[setFilterExpression],
|
||||
);
|
||||
|
||||
const queryData = useMemo(
|
||||
() =>
|
||||
getHostLogsQueryPayload({
|
||||
start: timeRange.startTime,
|
||||
end: timeRange.endTime,
|
||||
// this should use inputExpression to show suggestions correctly
|
||||
// while we don't accept the final expression yet
|
||||
expression: inputExpression,
|
||||
}).queryData,
|
||||
[timeRange.startTime, timeRange.endTime, inputExpression],
|
||||
);
|
||||
|
||||
const {
|
||||
logs,
|
||||
hasReachedEndOfLogs,
|
||||
isPaginating,
|
||||
currentPage,
|
||||
setIsPaginating,
|
||||
handleNewData,
|
||||
loadMoreLogs,
|
||||
queryPayload,
|
||||
} = useHandleLogsPagination({
|
||||
timeRange,
|
||||
filters,
|
||||
excludeFilterKeys: ['host.name'],
|
||||
basePayload,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
} = useInfiniteHostMetricLogs({
|
||||
expression: debouncedFilterExpression,
|
||||
startTime: timeRange.startTime,
|
||||
endTime: timeRange.endTime,
|
||||
});
|
||||
|
||||
const { data, isLoading, isFetching, isError } = useQuery({
|
||||
queryKey: [
|
||||
'hostMetricsLogs',
|
||||
timeRange.startTime,
|
||||
timeRange.endTime,
|
||||
filters,
|
||||
currentPage,
|
||||
],
|
||||
queryFn: () => GetMetricQueryRange(queryPayload, DEFAULT_ENTITY_VERSION),
|
||||
enabled: !!queryPayload,
|
||||
keepPreviousData: isPaginating,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.payload?.data?.newResult?.data?.result) {
|
||||
handleNewData(data.payload.data.newResult.data.result);
|
||||
}
|
||||
}, [data, handleNewData]);
|
||||
|
||||
useEffect(() => {
|
||||
setIsPaginating(false);
|
||||
}, [data, setIsPaginating]);
|
||||
|
||||
const handleScrollToLog = useScrollToLog({
|
||||
logs,
|
||||
virtuosoRef,
|
||||
@@ -122,22 +195,21 @@ function HostMetricsLogs({ timeRange, filters }: Props): JSX.Element {
|
||||
const renderFooter = useCallback(
|
||||
(): JSX.Element | null => (
|
||||
<>
|
||||
{isFetching ? (
|
||||
<div className="logs-loading-skeleton"> Loading more logs ... </div>
|
||||
) : hasReachedEndOfLogs ? (
|
||||
<div className="logs-loading-skeleton"> *** End *** </div>
|
||||
{isFetchingNextPage ? (
|
||||
<div className={styles.logsLoadingSkeleton}> Loading more logs ... </div>
|
||||
) : !hasNextPage && logs.length > 0 ? (
|
||||
<div className={styles.logsLoadingSkeleton}> *** End *** </div>
|
||||
) : null}
|
||||
</>
|
||||
),
|
||||
[isFetching, hasReachedEndOfLogs],
|
||||
[isFetchingNextPage, hasNextPage, logs.length],
|
||||
);
|
||||
|
||||
const renderContent = useMemo(
|
||||
() => (
|
||||
<Card bordered={false} className="host-metrics-logs-list-card">
|
||||
<Card bordered={false} className={styles.listCard}>
|
||||
<OverlayScrollbar isVirtuoso>
|
||||
<Virtuoso
|
||||
className="host-metrics-logs-virtuoso"
|
||||
key="host-metrics-logs-virtuoso"
|
||||
ref={virtuosoRef}
|
||||
data={logs}
|
||||
@@ -155,32 +227,55 @@ function HostMetricsLogs({ timeRange, filters }: Props): JSX.Element {
|
||||
[logs, loadMoreLogs, getItemContent, renderFooter],
|
||||
);
|
||||
|
||||
const showInitialLoading = isLoading || (isFetching && logs.length === 0);
|
||||
|
||||
return (
|
||||
<div className="host-metrics-logs">
|
||||
{isLoading && <LogsLoading />}
|
||||
{!isLoading && !isError && logs.length === 0 && <NoLogsContainer />}
|
||||
{isError && !isLoading && <LogsError />}
|
||||
{!isLoading && !isError && logs.length > 0 && (
|
||||
<div
|
||||
className="host-metrics-logs-list-container"
|
||||
data-log-detail-ignore="true"
|
||||
>
|
||||
{renderContent}
|
||||
</div>
|
||||
)}
|
||||
{selectedTab && activeLog && (
|
||||
<LogDetail
|
||||
log={activeLog}
|
||||
onClose={handleCloseLogDetail}
|
||||
logs={logs}
|
||||
onNavigateLog={handleSetActiveLog}
|
||||
selectedTab={selectedTab}
|
||||
onAddToQuery={onAddToQuery}
|
||||
onClickActionItem={onAddToQuery}
|
||||
onScrollToLog={handleScrollToLog}
|
||||
<>
|
||||
<div className={styles.header}>
|
||||
<DateTimeSelectionV2
|
||||
showAutoRefresh
|
||||
showRefreshText={false}
|
||||
hideShareModal
|
||||
isModalTimeSelection={isModalTimeSelection}
|
||||
onTimeChange={handleTimeChange}
|
||||
defaultRelativeTime="5m"
|
||||
modalSelectedInterval={selectedInterval}
|
||||
modalInitialStartTime={timeRange.startTime * 1000}
|
||||
modalInitialEndTime={timeRange.endTime * 1000}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<QuerySearch
|
||||
queryData={queryData}
|
||||
onChange={handleFilterChange}
|
||||
dataSource={DataSource.LOGS}
|
||||
/>
|
||||
|
||||
<div className={styles.logs}>
|
||||
{showInitialLoading && <LogsLoading />}
|
||||
{!showInitialLoading && !isError && logs.length === 0 && (
|
||||
<NoLogsContainer />
|
||||
)}
|
||||
{isError && !showInitialLoading && <LogsError />}
|
||||
{!showInitialLoading && !isError && logs.length > 0 && (
|
||||
<div className={styles.listContainer} data-log-detail-ignore="true">
|
||||
{renderContent}
|
||||
</div>
|
||||
)}
|
||||
{selectedTab && activeLog && (
|
||||
<LogDetail
|
||||
log={activeLog}
|
||||
onClose={handleCloseLogDetail}
|
||||
logs={logs}
|
||||
onNavigateLog={handleSetActiveLog}
|
||||
selectedTab={selectedTab}
|
||||
onAddToQuery={onAddToQuery}
|
||||
onClickActionItem={onAddToQuery}
|
||||
onScrollToLog={handleScrollToLog}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Typography } from 'antd';
|
||||
import { Ghost } from 'lucide-react';
|
||||
|
||||
const { Text } = Typography;
|
||||
import styles from './HostMetricLogs.module.scss';
|
||||
|
||||
export default function NoLogsContainer(): React.ReactElement {
|
||||
return (
|
||||
<div className="no-logs-found">
|
||||
<Text type="secondary">
|
||||
<div className={styles.noLogsFound}>
|
||||
<p>
|
||||
<Ghost size={24} color={Color.BG_AMBER_500} /> No logs found for this host
|
||||
in the selected time range.
|
||||
</Text>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,975 @@
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
|
||||
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import HostMetricsLogs from '../HostMetricsLogs';
|
||||
|
||||
jest.mock('react-virtuoso', () => {
|
||||
const actual = jest.requireActual('react-virtuoso');
|
||||
return {
|
||||
...actual,
|
||||
Virtuoso: ({
|
||||
data,
|
||||
itemContent,
|
||||
endReached,
|
||||
components,
|
||||
className,
|
||||
}: {
|
||||
data?: any[];
|
||||
itemContent?: (index: number, item: any) => React.ReactNode;
|
||||
endReached?: (index: number) => void;
|
||||
components?: { Footer?: React.ComponentType };
|
||||
className?: string;
|
||||
}): JSX.Element => (
|
||||
<div data-testid="virtuoso-mock" className={className}>
|
||||
{Array.isArray(data) &&
|
||||
data.map((item, index) => (
|
||||
<div key={item?.id ?? index} data-testid={`virtuoso-item-${index}`}>
|
||||
{itemContent?.(index, item)}
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
data-testid="virtuoso-end-reached"
|
||||
onClick={(): void => endReached?.((data?.length || 0) - 1)}
|
||||
>
|
||||
endReached
|
||||
</button>
|
||||
{components?.Footer ? <components.Footer /> : null}
|
||||
</div>
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
const QUERY_RANGE_URL = `${ENVIRONMENT.baseURL}/api/v5/query_range`;
|
||||
const FIELDS_KEYS_URL = `${ENVIRONMENT.baseURL}/api/v1/fields/keys`;
|
||||
const FIELDS_VALUES_URL = `${ENVIRONMENT.baseURL}/api/v1/fields/values`;
|
||||
|
||||
// Creates a V5 API response structure for raw logs data
|
||||
// The API response is wrapped in { data: { type: '...', data: { results: [...] } } }
|
||||
const createLogsResponse = ({
|
||||
offset = 0,
|
||||
pageSize = 100,
|
||||
hasMore = true,
|
||||
}: {
|
||||
offset?: number;
|
||||
pageSize?: number;
|
||||
hasMore?: boolean;
|
||||
}): any => {
|
||||
const itemsForThisPage = hasMore ? pageSize : Math.min(pageSize / 2, 10);
|
||||
|
||||
return {
|
||||
data: {
|
||||
type: 'raw',
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
queryName: 'A',
|
||||
rows: Array.from({ length: itemsForThisPage }, (_, index) => {
|
||||
const cumulativeIndex = offset + index;
|
||||
const baseTimestamp = new Date('2024-02-15T21:20:22Z').getTime();
|
||||
const currentTimestamp = new Date(
|
||||
baseTimestamp - cumulativeIndex * 1000,
|
||||
);
|
||||
const timestampString = currentTimestamp.toISOString();
|
||||
const id = `log-id-${cumulativeIndex}`;
|
||||
const logLevel = ['INFO', 'WARN', 'ERROR'][cumulativeIndex % 3];
|
||||
const service = ['frontend', 'backend', 'database'][cumulativeIndex % 3];
|
||||
|
||||
return {
|
||||
timestamp: timestampString,
|
||||
data: {
|
||||
attributes_bool: {},
|
||||
attributes_float64: {},
|
||||
attributes_int64: {},
|
||||
attributes_string: {
|
||||
host_name: 'test-host',
|
||||
log_level: logLevel,
|
||||
service,
|
||||
},
|
||||
body: `${timestampString} ${logLevel} ${service} Log message ${cumulativeIndex}`,
|
||||
id,
|
||||
resources_string: {
|
||||
'host.name': 'test-host',
|
||||
},
|
||||
severity_number: [9, 13, 17][cumulativeIndex % 3],
|
||||
severity_text: logLevel,
|
||||
span_id: `span-${cumulativeIndex}`,
|
||||
trace_flags: 0,
|
||||
trace_id: `trace-${cumulativeIndex}`,
|
||||
},
|
||||
};
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const createEmptyLogsResponse = (): any => ({
|
||||
data: {
|
||||
type: 'raw',
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
queryName: 'A',
|
||||
rows: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const defaultProps = {
|
||||
initialExpression: 'host_name = "test-host"',
|
||||
timeRange: {
|
||||
startTime: 1708000000,
|
||||
endTime: 1708003600,
|
||||
},
|
||||
isModalTimeSelection: false,
|
||||
handleTimeChange: jest.fn(),
|
||||
selectedInterval: '15m' as const,
|
||||
};
|
||||
|
||||
// Mock OverlayScrollbar to avoid scroll behavior issues in tests
|
||||
jest.mock('components/OverlayScrollbar/OverlayScrollbar', () => ({
|
||||
__esModule: true,
|
||||
default: ({ children }: { children: React.ReactNode }): JSX.Element => (
|
||||
<div>{children}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
jest.mock('container/TopNav/DateTimeSelectionV2/index.tsx', () => ({
|
||||
__esModule: true,
|
||||
default: ({
|
||||
onTimeChange,
|
||||
}: {
|
||||
onTimeChange?: (interval: string, dateTimeRange?: [number, number]) => void;
|
||||
}): JSX.Element => {
|
||||
return (
|
||||
<div className="datetime-section" data-testid="datetime-selection">
|
||||
<button
|
||||
data-testid="time-picker-btn"
|
||||
onClick={(): void => {
|
||||
onTimeChange?.('5m');
|
||||
}}
|
||||
>
|
||||
Select Time
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
const createFieldKeysResponse = (): any => ({
|
||||
status: 'success',
|
||||
data: {
|
||||
complete: true,
|
||||
keys: {},
|
||||
},
|
||||
});
|
||||
|
||||
const createFieldValuesResponse = (): any => ({
|
||||
status: 'success',
|
||||
data: {
|
||||
values: {
|
||||
stringValues: [],
|
||||
numberValues: [],
|
||||
boolValues: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const renderComponent = (
|
||||
props = defaultProps,
|
||||
searchParams?: Record<string, string>,
|
||||
): ReturnType<typeof render> =>
|
||||
render(
|
||||
<NuqsTestingAdapter searchParams={searchParams} hasMemory>
|
||||
<VirtuosoMockContext.Provider
|
||||
value={{ viewportHeight: 600, itemHeight: 50 }}
|
||||
>
|
||||
<HostMetricsLogs {...props} />
|
||||
</VirtuosoMockContext.Provider>
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
|
||||
describe('HostMetricsLogs', () => {
|
||||
beforeEach(() => {
|
||||
window.history.pushState({}, 'Test', '/');
|
||||
server.use(
|
||||
rest.get(FIELDS_KEYS_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createFieldKeysResponse())),
|
||||
),
|
||||
rest.get(FIELDS_VALUES_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createFieldValuesResponse())),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
describe('loading state', () => {
|
||||
it('should show loading state while fetching logs', async () => {
|
||||
let resolveRequest: (value: any) => void;
|
||||
const pendingPromise = new Promise((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
});
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (_, res, ctx) => {
|
||||
await pendingPromise;
|
||||
return res(ctx.status(200), ctx.json(createLogsResponse({})));
|
||||
}),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
expect(screen.getByText('pending_data_placeholder')).toBeInTheDocument();
|
||||
|
||||
act(() => {
|
||||
resolveRequest!(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('empty state', () => {
|
||||
it('should show no logs message when no logs are returned', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createEmptyLogsResponse())),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/No logs found for this host/i),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('error state', () => {
|
||||
it('should show error state when API returns error', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(500), ctx.json({ error: 'Internal Server Error' })),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Something went wrong/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('success state', () => {
|
||||
it('should render logs when API returns data', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 }))),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Log message 0/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should render initial expression in QuerySearch editor', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 }))),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
const editorText =
|
||||
document.querySelector('.query-where-clause-editor')?.textContent || '';
|
||||
expect(editorText).toContain('host_name');
|
||||
expect(editorText).toContain('test-host');
|
||||
});
|
||||
});
|
||||
|
||||
it('should render the filter section', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 }))),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
document.querySelector('.code-mirror-where-clause'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should render date time selection component', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 }))),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
// DateTimeSelectionV2 renders a time picker button
|
||||
expect(document.querySelector('.datetime-section')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('pagination', () => {
|
||||
it('should send correct offset for pagination', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
|
||||
const querySpec = payload.compositeQuery?.queries?.[0]?.spec;
|
||||
const offset = querySpec?.offset ?? 0;
|
||||
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(
|
||||
createLogsResponse({
|
||||
offset,
|
||||
pageSize: 100,
|
||||
hasMore: offset === 0,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestPayloads.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
const firstPayload = requestPayloads[0];
|
||||
const querySpec = firstPayload.compositeQuery?.queries?.[0]?.spec;
|
||||
expect(querySpec?.offset).toBe(0);
|
||||
});
|
||||
|
||||
it('should fetch next page when virtuoso endReached is triggered', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
|
||||
const querySpec = payload.compositeQuery?.queries?.[0]?.spec;
|
||||
const offset = querySpec?.offset ?? 0;
|
||||
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(
|
||||
createLogsResponse({
|
||||
offset,
|
||||
pageSize: 100,
|
||||
hasMore: offset === 0,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Log message 0/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(requestPayloads[0]?.compositeQuery?.queries?.[0]?.spec?.offset).toBe(
|
||||
0,
|
||||
);
|
||||
|
||||
await userEvent.click(screen.getByTestId('virtuoso-end-reached'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestPayloads.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
expect(requestPayloads[1]?.compositeQuery?.queries?.[0]?.spec?.offset).toBe(
|
||||
100,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('filter expression', () => {
|
||||
it('should include initial expression in the query', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
|
||||
return res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 })));
|
||||
}),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestPayloads.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
const firstPayload = requestPayloads[0];
|
||||
const querySpec = firstPayload.compositeQuery?.queries?.[0]?.spec;
|
||||
|
||||
expect(querySpec?.filter?.expression).toContain('host_name = "test-host"');
|
||||
});
|
||||
|
||||
it('should load expression from URL and persist it in the query', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
|
||||
const querySpec = payload.compositeQuery?.queries?.[0]?.spec;
|
||||
const offset = querySpec?.offset ?? 0;
|
||||
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(
|
||||
createLogsResponse({
|
||||
offset,
|
||||
pageSize: 100,
|
||||
hasMore: offset === 0,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const urlExpression = 'service = "from-url"';
|
||||
|
||||
renderComponent(defaultProps, { hostMetricsLogsExpr: urlExpression });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestPayloads.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
expect(
|
||||
requestPayloads[0]?.compositeQuery?.queries?.[0]?.spec?.filter?.expression,
|
||||
).toContain(urlExpression);
|
||||
|
||||
await userEvent.click(screen.getByTestId('virtuoso-end-reached'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestPayloads.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
expect(
|
||||
requestPayloads[1]?.compositeQuery?.queries?.[0]?.spec?.filter?.expression,
|
||||
).toContain(urlExpression);
|
||||
});
|
||||
|
||||
it('should use custom expression when provided', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
|
||||
return res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 })));
|
||||
}),
|
||||
);
|
||||
|
||||
const customExpression = 'service = "custom-service"';
|
||||
|
||||
renderComponent({
|
||||
...defaultProps,
|
||||
initialExpression: customExpression,
|
||||
});
|
||||
|
||||
// Wait for debounce and potential re-renders to settle
|
||||
await waitFor(
|
||||
() => {
|
||||
const hasCustomExpression = requestPayloads.some((payload) => {
|
||||
const querySpec = payload.compositeQuery?.queries?.[0]?.spec;
|
||||
return querySpec?.filter?.expression?.includes('custom-service');
|
||||
});
|
||||
expect(hasCustomExpression).toBe(true);
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('time range', () => {
|
||||
it('should include correct time range in the query', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
|
||||
return res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 })));
|
||||
}),
|
||||
);
|
||||
|
||||
const customTimeRange = {
|
||||
startTime: 1700000000,
|
||||
endTime: 1700003600,
|
||||
};
|
||||
|
||||
renderComponent({
|
||||
...defaultProps,
|
||||
timeRange: customTimeRange,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestPayloads.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
const firstPayload = requestPayloads[0];
|
||||
|
||||
// V5 API expects milliseconds (seconds * 1000)
|
||||
expect(firstPayload.start).toBe(customTimeRange.startTime * 1000);
|
||||
expect(firstPayload.end).toBe(customTimeRange.endTime * 1000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('query structure', () => {
|
||||
it('should send correct query structure to the API', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
|
||||
return res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 })));
|
||||
}),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestPayloads.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
const firstPayload = requestPayloads[0];
|
||||
const querySpec = firstPayload.compositeQuery?.queries?.[0]?.spec;
|
||||
|
||||
expect(querySpec?.signal).toBe('logs');
|
||||
expect(querySpec?.order).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
key: expect.objectContaining({ name: 'timestamp' }),
|
||||
direction: 'desc',
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('should send request type as raw for logs list', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
|
||||
return res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 })));
|
||||
}),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestPayloads.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
const firstPayload = requestPayloads[0];
|
||||
expect(firstPayload.requestType).toBe('raw');
|
||||
});
|
||||
|
||||
it('should include pageSize in the query', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
|
||||
return res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 })));
|
||||
}),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestPayloads.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
const firstPayload = requestPayloads[0];
|
||||
const querySpec = firstPayload.compositeQuery?.queries?.[0]?.spec;
|
||||
|
||||
// Should have a limit set for pagination
|
||||
expect(querySpec?.limit).toBeDefined();
|
||||
expect(typeof querySpec?.limit).toBe('number');
|
||||
});
|
||||
});
|
||||
|
||||
describe('component props', () => {
|
||||
it('should render datetime section with isModalTimeSelection', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 }))),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent({
|
||||
...defaultProps,
|
||||
isModalTimeSelection: true,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector('.datetime-section')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should render component with handleTimeChange', async () => {
|
||||
const mockHandleTimeChange = jest.fn();
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 }))),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent({
|
||||
...defaultProps,
|
||||
handleTimeChange: mockHandleTimeChange,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector('.datetime-section')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('log detail interactions', () => {
|
||||
it('should open log detail drawer when clicking on a log', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 }))),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
// Wait for logs to render
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Log message 0/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click on the first log
|
||||
const logElement = screen.getByText(/Log message 0/);
|
||||
await userEvent.click(logElement);
|
||||
|
||||
// Log detail drawer should open - it contains "Log details" title
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Log details')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should close log detail drawer when clicking on the same log again', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 }))),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
// Wait for logs to render
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Log message 0/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click on the first log to open
|
||||
const logElement = screen.getByText(/Log message 0/);
|
||||
await userEvent.click(logElement);
|
||||
|
||||
// Wait for drawer to open
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Log details')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click on the same log to close (through the close button)
|
||||
const closeButton = document.querySelector('.ant-drawer-close');
|
||||
if (closeButton) {
|
||||
await userEvent.click(closeButton);
|
||||
}
|
||||
|
||||
// Drawer should close
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Log details')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should display log body in detail drawer', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 }))),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
// Wait for logs to render
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Log message 0/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click on the first log to open drawer
|
||||
const logElement = screen.getByText(/Log message 0/);
|
||||
await userEvent.click(logElement);
|
||||
|
||||
// Wait for drawer to open
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Log details')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Verify the drawer tabs are displayed
|
||||
// The drawer should show the Overview tab
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Overview')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Verify other tabs are present
|
||||
expect(screen.getByText('JSON')).toBeInTheDocument();
|
||||
expect(screen.getByText('Context')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('log detail filter actions', () => {
|
||||
it('should apply filter-in from log detail and close the drawer', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
return res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 })));
|
||||
}),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Log message 0/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText(/Log message 0/));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Log details')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const serviceRow = await waitFor(() => {
|
||||
const attributeNameCells = Array.from(
|
||||
document.querySelectorAll('.attribute-name'),
|
||||
);
|
||||
const serviceCell = attributeNameCells.find((cell) =>
|
||||
(cell.textContent || '').toLowerCase().includes('service'),
|
||||
);
|
||||
const row = serviceCell?.closest('tr');
|
||||
if (!row) {
|
||||
throw new Error('Service attribute row not found');
|
||||
}
|
||||
return row;
|
||||
});
|
||||
|
||||
const filterButtons = serviceRow.querySelectorAll('button.filter-btn');
|
||||
expect(filterButtons?.length).toBeGreaterThanOrEqual(2);
|
||||
|
||||
await userEvent.click(filterButtons[0] as HTMLButtonElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Log details')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
const matched = requestPayloads.some((payload) => {
|
||||
const expression =
|
||||
payload.compositeQuery?.queries?.[0]?.spec?.filter?.expression || '';
|
||||
return (
|
||||
(expression.includes('attributes_string.service') ||
|
||||
expression.includes('service')) &&
|
||||
expression.includes("('frontend')") &&
|
||||
expression.includes('IN')
|
||||
);
|
||||
});
|
||||
expect(matched).toBe(true);
|
||||
},
|
||||
{ timeout: 2500 },
|
||||
);
|
||||
});
|
||||
|
||||
it('should apply filter-out from log detail and close the drawer', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
return res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 })));
|
||||
}),
|
||||
);
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Log message 0/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText(/Log message 0/));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Log details')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const serviceRow = await waitFor(() => {
|
||||
const attributeNameCells = Array.from(
|
||||
document.querySelectorAll('.attribute-name'),
|
||||
);
|
||||
const serviceCell = attributeNameCells.find((cell) =>
|
||||
(cell.textContent || '').toLowerCase().includes('service'),
|
||||
);
|
||||
const row = serviceCell?.closest('tr');
|
||||
if (!row) {
|
||||
throw new Error('Service attribute row not found');
|
||||
}
|
||||
return row;
|
||||
});
|
||||
|
||||
const filterButtons = serviceRow.querySelectorAll('button.filter-btn');
|
||||
expect(filterButtons?.length).toBeGreaterThanOrEqual(2);
|
||||
|
||||
// the second button that represents filter out
|
||||
await userEvent.click(filterButtons[1] as HTMLButtonElement);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Log details')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
const matched = requestPayloads.some((payload) => {
|
||||
const expression =
|
||||
payload.compositeQuery?.queries?.[0]?.spec?.filter?.expression || '';
|
||||
return (
|
||||
(expression.includes('attributes_string.service') ||
|
||||
expression.includes('service')) &&
|
||||
expression.includes("('frontend')") &&
|
||||
(expression.includes('NIN') || expression.includes('NOT_IN'))
|
||||
);
|
||||
});
|
||||
expect(matched).toBe(true);
|
||||
},
|
||||
{ timeout: 2500 },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('time range change', () => {
|
||||
it('should use different time ranges for different renders', async () => {
|
||||
const requestPayloads: any[] = [];
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const payload = await req.json();
|
||||
requestPayloads.push(payload);
|
||||
return res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 })));
|
||||
}),
|
||||
);
|
||||
|
||||
// First render with initial time range
|
||||
const { unmount } = renderComponent();
|
||||
|
||||
// Wait for initial fetch
|
||||
await waitFor(() => {
|
||||
expect(requestPayloads.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
const firstStartTime = requestPayloads[0].start;
|
||||
expect(firstStartTime).toBe(defaultProps.timeRange.startTime * 1000);
|
||||
|
||||
// Unmount and render again with different time range
|
||||
unmount();
|
||||
|
||||
const newTimeRange = {
|
||||
startTime: 1709000000,
|
||||
endTime: 1709003600,
|
||||
};
|
||||
|
||||
renderComponent({
|
||||
...defaultProps,
|
||||
timeRange: newTimeRange,
|
||||
});
|
||||
|
||||
// Wait for fetch with new time range
|
||||
await waitFor(() => {
|
||||
const hasNewTimeRange = requestPayloads.some(
|
||||
(p) => p.start === newTimeRange.startTime * 1000,
|
||||
);
|
||||
expect(hasNewTimeRange).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should call handleTimeChange callback when time picker is clicked', async () => {
|
||||
const mockHandleTimeChange = jest.fn();
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 }))),
|
||||
),
|
||||
);
|
||||
|
||||
renderComponent({
|
||||
...defaultProps,
|
||||
handleTimeChange: mockHandleTimeChange,
|
||||
});
|
||||
|
||||
// Wait for component to render
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('time-picker-btn')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click the time picker button (from mock)
|
||||
await userEvent.click(screen.getByTestId('time-picker-btn'));
|
||||
|
||||
// Verify the callback was called
|
||||
expect(mockHandleTimeChange).toHaveBeenCalledWith('5m');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,311 @@
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
|
||||
import { useInfiniteHostMetricLogs } from '../hooks';
|
||||
|
||||
const QUERY_RANGE_URL = `${ENVIRONMENT.baseURL}/api/v5/query_range`;
|
||||
|
||||
const createLogsResponse = ({
|
||||
offset = 0,
|
||||
pageSize = 100,
|
||||
hasMore = true,
|
||||
}: {
|
||||
offset?: number;
|
||||
pageSize?: number;
|
||||
hasMore?: boolean;
|
||||
}): any => {
|
||||
const itemsForThisPage = hasMore ? pageSize : pageSize / 2;
|
||||
|
||||
return {
|
||||
data: {
|
||||
type: 'raw',
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
queryName: 'A',
|
||||
rows: Array.from({ length: itemsForThisPage }, (_, index) => {
|
||||
const cumulativeIndex = offset + index;
|
||||
return {
|
||||
timestamp: new Date(Date.now() - cumulativeIndex * 1000).toISOString(),
|
||||
data: {
|
||||
body: `Log message ${cumulativeIndex}`,
|
||||
id: `log-${cumulativeIndex}`,
|
||||
severity_text: 'INFO',
|
||||
},
|
||||
};
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const createEmptyResponse = (): any => ({
|
||||
data: {
|
||||
type: 'raw',
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
queryName: 'A',
|
||||
rows: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createWrapper = (): React.FC<{ children: React.ReactNode }> => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return function Wrapper({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
describe('useInfiniteHostMetricLogs', () => {
|
||||
const defaultParams = {
|
||||
expression: 'host_name = "test-host"',
|
||||
startTime: 1708000000,
|
||||
endTime: 1708003600,
|
||||
};
|
||||
|
||||
describe('initial state', () => {
|
||||
it('should return initial loading state', () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.delay(100), ctx.status(200), ctx.json(createLogsResponse({}))),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useInfiniteHostMetricLogs(defaultParams),
|
||||
{
|
||||
wrapper: createWrapper(),
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.current.isLoading).toBe(true);
|
||||
expect(result.current.logs).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('successful data fetching', () => {
|
||||
it('should return logs after successful fetch', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createLogsResponse({ pageSize: 5 }))),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useInfiniteHostMetricLogs(defaultParams),
|
||||
{
|
||||
wrapper: createWrapper(),
|
||||
},
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.logs.length).toBe(5);
|
||||
expect(result.current.isError).toBe(false);
|
||||
});
|
||||
|
||||
it('should set hasNextPage based on response size', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json(createLogsResponse({ pageSize: 100, hasMore: true })),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useInfiniteHostMetricLogs(defaultParams),
|
||||
{
|
||||
wrapper: createWrapper(),
|
||||
},
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.hasNextPage).toBe(true);
|
||||
});
|
||||
|
||||
it('should not have next page when response is smaller than page size', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(
|
||||
ctx.status(200),
|
||||
ctx.json(createLogsResponse({ pageSize: 100, hasMore: false })),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useInfiniteHostMetricLogs(defaultParams),
|
||||
{
|
||||
wrapper: createWrapper(),
|
||||
},
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.hasNextPage).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('empty state', () => {
|
||||
it('should return empty logs array when no data', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(createEmptyResponse())),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useInfiniteHostMetricLogs(defaultParams),
|
||||
{
|
||||
wrapper: createWrapper(),
|
||||
},
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.logs).toEqual([]);
|
||||
expect(result.current.hasNextPage).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('error handling', () => {
|
||||
it('should set isError on API failure', async () => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) =>
|
||||
res(ctx.status(500), ctx.json({ error: 'Internal Server Error' })),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useInfiniteHostMetricLogs(defaultParams),
|
||||
{
|
||||
wrapper: createWrapper(),
|
||||
},
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isError).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.logs).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('query disabled state', () => {
|
||||
it('should not fetch when expression is empty', async () => {
|
||||
const requestCount = { count: 0 };
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) => {
|
||||
requestCount.count += 1;
|
||||
return res(ctx.status(200), ctx.json(createLogsResponse({})));
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useInfiniteHostMetricLogs({
|
||||
...defaultParams,
|
||||
expression: '',
|
||||
}),
|
||||
{
|
||||
wrapper: createWrapper(),
|
||||
},
|
||||
);
|
||||
|
||||
// Wait a bit to ensure no request is made
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, 300);
|
||||
});
|
||||
|
||||
expect(requestCount.count).toBe(0);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('load more functionality', () => {
|
||||
it('should fetch next page when loadMoreLogs is called', async () => {
|
||||
const requestCount = { count: 0 };
|
||||
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_, res, ctx) => {
|
||||
requestCount.count += 1;
|
||||
if (requestCount.count === 1) {
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(
|
||||
createLogsResponse({ offset: 0, pageSize: 100, hasMore: true }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(
|
||||
createLogsResponse({ offset: 100, pageSize: 100, hasMore: false }),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useInfiniteHostMetricLogs(defaultParams),
|
||||
{
|
||||
wrapper: createWrapper(),
|
||||
},
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.logs.length).toBe(100);
|
||||
expect(result.current.hasNextPage).toBe(true);
|
||||
expect(requestCount.count).toBe(1);
|
||||
|
||||
act(() => {
|
||||
result.current.loadMoreLogs();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.logs.length).toBe(150);
|
||||
});
|
||||
|
||||
expect(result.current.hasNextPage).toBe(false);
|
||||
expect(requestCount.count).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { DEFAULT_PER_PAGE_VALUE } from 'container/Controls/config';
|
||||
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
|
||||
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
@@ -6,56 +7,82 @@ import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
export const getHostLogsQueryPayload = (
|
||||
start: number,
|
||||
end: number,
|
||||
filters: IBuilderQuery['filters'],
|
||||
): GetQueryResultsProps => ({
|
||||
graphType: PANEL_TYPES.LIST,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
query: {
|
||||
clickhouse_sql: [],
|
||||
promql: [],
|
||||
builder: {
|
||||
queryData: [
|
||||
{
|
||||
dataSource: DataSource.LOGS,
|
||||
queryName: 'A',
|
||||
aggregateOperator: 'noop',
|
||||
aggregateAttribute: {
|
||||
id: '------false',
|
||||
dataType: DataTypes.String,
|
||||
key: '',
|
||||
type: '',
|
||||
},
|
||||
timeAggregation: 'rate',
|
||||
spaceAggregation: 'sum',
|
||||
functions: [],
|
||||
filters,
|
||||
expression: 'A',
|
||||
disabled: false,
|
||||
stepInterval: 60,
|
||||
having: [],
|
||||
limit: null,
|
||||
orderBy: [
|
||||
{
|
||||
columnName: 'timestamp',
|
||||
order: 'desc',
|
||||
},
|
||||
],
|
||||
groupBy: [],
|
||||
legend: '',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
offset: 0,
|
||||
pageSize: 100,
|
||||
},
|
||||
],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
id: uuidv4(),
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
},
|
||||
export interface HostLogsQueryParams {
|
||||
start: number;
|
||||
end: number;
|
||||
expression: string;
|
||||
offset?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export const getHostLogsQueryPayload = ({
|
||||
start,
|
||||
end,
|
||||
});
|
||||
expression,
|
||||
offset = 0,
|
||||
pageSize = DEFAULT_PER_PAGE_VALUE,
|
||||
}: HostLogsQueryParams): {
|
||||
query: GetQueryResultsProps;
|
||||
queryData: IBuilderQuery;
|
||||
} => {
|
||||
const queryData: IBuilderQuery = {
|
||||
dataSource: DataSource.LOGS,
|
||||
queryName: 'A',
|
||||
aggregateOperator: 'noop',
|
||||
aggregateAttribute: {
|
||||
id: '------false',
|
||||
dataType: DataTypes.String,
|
||||
key: '',
|
||||
type: '',
|
||||
},
|
||||
timeAggregation: 'rate',
|
||||
spaceAggregation: 'sum',
|
||||
functions: [],
|
||||
filter: { expression },
|
||||
expression,
|
||||
having: {
|
||||
expression: '',
|
||||
},
|
||||
disabled: false,
|
||||
stepInterval: 60,
|
||||
limit: null,
|
||||
orderBy: [
|
||||
{
|
||||
columnName: 'timestamp',
|
||||
order: 'desc',
|
||||
},
|
||||
{
|
||||
columnName: 'id',
|
||||
order: 'desc',
|
||||
},
|
||||
],
|
||||
groupBy: [],
|
||||
legend: '',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
offset,
|
||||
pageSize,
|
||||
};
|
||||
|
||||
return {
|
||||
query: {
|
||||
graphType: PANEL_TYPES.LIST,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
query: {
|
||||
clickhouse_sql: [],
|
||||
promql: [],
|
||||
builder: {
|
||||
queryData: [queryData],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
id: uuidv4(),
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
},
|
||||
start,
|
||||
end,
|
||||
},
|
||||
queryData,
|
||||
};
|
||||
};
|
||||
|
||||
export const HOST_METRICS_LOGS_EXPR_QUERY_KEY = 'hostMetricsLogsExpr';
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useInfiniteQuery } from 'react-query';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { DEFAULT_PER_PAGE_VALUE } from 'container/Controls/config';
|
||||
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
|
||||
import { getHostLogsQueryPayload } from './constants';
|
||||
|
||||
export function useInfiniteHostMetricLogs({
|
||||
expression,
|
||||
startTime,
|
||||
endTime,
|
||||
}: {
|
||||
expression: string;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
}): {
|
||||
logs: ILog[];
|
||||
isLoading: boolean;
|
||||
isFetching: boolean;
|
||||
isFetchingNextPage: boolean;
|
||||
isError: boolean;
|
||||
hasNextPage: boolean;
|
||||
loadMoreLogs: () => void;
|
||||
} {
|
||||
const {
|
||||
data,
|
||||
isLoading,
|
||||
isFetching,
|
||||
isFetchingNextPage,
|
||||
isError,
|
||||
hasNextPage,
|
||||
fetchNextPage,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: ['hostMetricsLogs', startTime, endTime, expression],
|
||||
queryFn: async ({ pageParam = 0 }) => {
|
||||
const { query } = getHostLogsQueryPayload({
|
||||
start: startTime,
|
||||
end: endTime,
|
||||
expression,
|
||||
offset: pageParam,
|
||||
pageSize: DEFAULT_PER_PAGE_VALUE,
|
||||
});
|
||||
return GetMetricQueryRange(query, ENTITY_VERSION_V5);
|
||||
},
|
||||
getNextPageParam: (lastPage, allPages) => {
|
||||
const list = lastPage?.payload?.data?.newResult?.data?.result?.[0]?.list;
|
||||
if (!list || list.length < DEFAULT_PER_PAGE_VALUE) {
|
||||
return undefined;
|
||||
}
|
||||
return allPages.length * DEFAULT_PER_PAGE_VALUE;
|
||||
},
|
||||
enabled: !!expression,
|
||||
});
|
||||
|
||||
const logs = useMemo<ILog[]>(() => {
|
||||
if (!data?.pages) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return data.pages.flatMap((page) => {
|
||||
const list = page?.payload?.data?.newResult?.data?.result?.[0]?.list;
|
||||
if (!list) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return list.map(
|
||||
(item) =>
|
||||
({
|
||||
...item.data,
|
||||
timestamp: item.timestamp,
|
||||
} as ILog),
|
||||
);
|
||||
});
|
||||
}, [data?.pages]);
|
||||
|
||||
const loadMoreLogs = useCallback(() => {
|
||||
if (hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage();
|
||||
}
|
||||
}, [hasNextPage, isFetchingNextPage, fetchNextPage]);
|
||||
|
||||
return {
|
||||
logs,
|
||||
isLoading,
|
||||
isFetching,
|
||||
isFetchingNextPage,
|
||||
isError,
|
||||
hasNextPage: !!hasNextPage,
|
||||
loadMoreLogs,
|
||||
};
|
||||
}
|
||||
@@ -89,7 +89,7 @@ function HostsList(): JSX.Element {
|
||||
...baseQuery,
|
||||
limit: pageSize,
|
||||
offset: (currentPage - 1) * pageSize,
|
||||
filters,
|
||||
filters: filters?.items?.length ? filters : undefined,
|
||||
start: Math.floor(minTime / 1000000),
|
||||
end: Math.floor(maxTime / 1000000),
|
||||
orderBy,
|
||||
@@ -97,15 +97,6 @@ function HostsList(): JSX.Element {
|
||||
}, [pageSize, currentPage, filters, minTime, maxTime, orderBy]);
|
||||
|
||||
const queryKey = useMemo(() => {
|
||||
if (selectedHostName) {
|
||||
return [
|
||||
'hostList',
|
||||
String(pageSize),
|
||||
String(currentPage),
|
||||
JSON.stringify(filters),
|
||||
JSON.stringify(orderBy),
|
||||
];
|
||||
}
|
||||
return [
|
||||
'hostList',
|
||||
String(pageSize),
|
||||
@@ -115,15 +106,7 @@ function HostsList(): JSX.Element {
|
||||
String(minTime),
|
||||
String(maxTime),
|
||||
];
|
||||
}, [
|
||||
pageSize,
|
||||
currentPage,
|
||||
filters,
|
||||
orderBy,
|
||||
selectedHostName,
|
||||
minTime,
|
||||
maxTime,
|
||||
]);
|
||||
}, [pageSize, currentPage, filters, orderBy, minTime, maxTime]);
|
||||
|
||||
const { data, isFetching, isLoading, isError } = useGetHostList(
|
||||
query as HostListPayload,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Provider } from 'react-redux';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { render } from '@testing-library/react';
|
||||
import * as useGetHostListHooks from 'hooks/infraMonitoring/useGetHostList';
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
|
||||
import * as appContextHooks from 'providers/App/App';
|
||||
import * as timezoneHooks from 'providers/Timezone';
|
||||
import store from 'store';
|
||||
@@ -130,26 +131,30 @@ jest.spyOn(appContextHooks, 'useAppContext').mockReturnValue({
|
||||
describe('HostsList', () => {
|
||||
it('renders hosts list table', () => {
|
||||
const { container } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter>
|
||||
<Provider store={store}>
|
||||
<HostsList />
|
||||
</Provider>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
<NuqsTestingAdapter>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter>
|
||||
<Provider store={store}>
|
||||
<HostsList />
|
||||
</Provider>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
expect(container.querySelector('.hosts-list-table')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders filters', () => {
|
||||
const { container } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter>
|
||||
<Provider store={store}>
|
||||
<HostsList />
|
||||
</Provider>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
<NuqsTestingAdapter>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter>
|
||||
<Provider store={store}>
|
||||
<HostsList />
|
||||
</Provider>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
expect(container.querySelector('.filters')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user