Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use react query for loading preview chart data #153045

Merged
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { niceTimeFormatter, TooltipValue } from '@elastic/charts';
import { Theme, LIGHT_THEME, DARK_THEME } from '@elastic/charts';
import moment from 'moment';
import { i18n } from '@kbn/i18n';
import { EuiText } from '@elastic/eui';
import { EuiLoadingChart, EuiText } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
import { sum, min as getMin, max as getMax } from 'lodash';
import { formatNumber } from '../../../../common/formatters/number';
Expand Down Expand Up @@ -119,7 +119,7 @@ export const LoadingState = () => {
return (
<EmptyContainer>
<EuiText color="subdued" data-test-subj="loadingData">
<FormattedMessage id="xpack.infra.alerts.charts.loadingMessage" defaultMessage="Loading" />
<EuiLoadingChart size="m" />
</EuiText>
</EmptyContainer>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const mockResponse = {
};

jest.mock('../hooks/use_metrics_explorer_chart_data', () => ({
useMetricsExplorerChartData: () => ({ loading: false, data: mockResponse }),
useMetricsExplorerChartData: () => ({ loading: false, data: { pages: [mockResponse] } }),
}));

describe('ExpressionChart', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import React, { useMemo, useCallback } from 'react';
import React from 'react';
import { Axis, Chart, niceTimeFormatter, Position, Settings } from '@elastic/charts';
import { EuiText } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
Expand Down Expand Up @@ -52,16 +52,34 @@ export const ExpressionChart: React.FC<Props> = ({
filterQuery,
groupBy,
}) => {
const { loading, data } = useMetricsExplorerChartData(
const { uiSettings } = useKibanaContextForPlugin().services;

const { isLoading, data } = useMetricsExplorerChartData(
expression,
derivedIndexPattern,
source,
filterQuery,
groupBy
);

const { uiSettings } = useKibanaContextForPlugin().services;
if (isLoading) {
return <LoadingState />;
}

if (!data) {
return <NoDataState />;
}

const isDarkMode = uiSettings?.get('theme:darkMode') || false;
const firstSeries = first(first(data.pages)!.series);
// Creating a custom series where the ID is changed to 0
// so that we can get a proper domain
if (!firstSeries || !firstSeries.rows || firstSeries.rows.length === 0) {
return <NoDataState />;
}

const firstTimestamp = first(firstSeries.rows)!.timestamp;
const lastTimestamp = last(firstSeries.rows)!.timestamp;
const metric: MetricsExplorerOptionsMetric = {
field: expression.metric,
aggregation: expression.aggType as MetricsExplorerAggregation,
Expand All @@ -71,41 +89,16 @@ export const ExpressionChart: React.FC<Props> = ({
if (metric.aggregation === 'custom') {
metric.label = expression.label || CUSTOM_EQUATION;
}
const isDarkMode = uiSettings?.get('theme:darkMode') || false;
const dateFormatter = useMemo(() => {
const firstSeries = first(data?.series);
const firstTimestamp = first(firstSeries?.rows)?.timestamp;
const lastTimestamp = last(firstSeries?.rows)?.timestamp;

if (firstTimestamp == null || lastTimestamp == null) {
return (value: number) => `${value}`;
}

return niceTimeFormatter([firstTimestamp, lastTimestamp]);
}, [data?.series]);

/* eslint-disable-next-line react-hooks/exhaustive-deps */
const yAxisFormater = useCallback(createFormatterForMetric(metric), [expression]);

if (loading) {
return <LoadingState />;
}

if (!data) {
return <NoDataState />;
}
const dateFormatter =
firstTimestamp == null || lastTimestamp == null
? (value: number) => `${value}`
: niceTimeFormatter([firstTimestamp, lastTimestamp]);

const criticalThresholds = expression.threshold.slice().sort();
const warningThresholds = expression.warningThreshold?.slice().sort() ?? [];
const thresholds = [...criticalThresholds, ...warningThresholds].sort();

// Creating a custom series where the ID is changed to 0
// so that we can get a proper domian
const firstSeries = first(data.series);
if (!firstSeries || !firstSeries.rows || firstSeries.rows.length === 0) {
return <NoDataState />;
}

const series = {
...firstSeries,
rows: firstSeries.rows.map((row) => {
Expand All @@ -117,8 +110,6 @@ export const ExpressionChart: React.FC<Props> = ({
}),
};

const firstTimestamp = first(firstSeries.rows)!.timestamp;
const lastTimestamp = last(firstSeries.rows)!.timestamp;
const dataDomain = calculateDomain(series, [metric], false);
const domain = {
max: Math.max(dataDomain.max, last(thresholds) || dataDomain.max) * 1.1, // add 10% headroom.
Expand Down Expand Up @@ -171,7 +162,12 @@ export const ExpressionChart: React.FC<Props> = ({
showOverlappingTicks={true}
tickFormat={dateFormatter}
/>
<Axis id={'values'} position={Position.Left} tickFormat={yAxisFormater} domain={domain} />
<Axis
id={'values'}
position={Position.Left}
tickFormat={createFormatterForMetric(metric)}
domain={domain}
/>
<Settings tooltip={tooltipProps} theme={getChartTheme(isDarkMode)} />
</Chart>
</ChartContainer>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@
* 2.0.
*/

import DateMath from '@kbn/datemath';
import { DataViewBase } from '@kbn/es-query';
import { useMemo } from 'react';
import { MetricExpressionCustomMetric } from '../../../../common/alerting/metrics';
import { MetricsSourceConfiguration } from '../../../../common/metrics_sources';
import { MetricExpression } from '../types';
import { MetricsExplorerOptions } from '../../../pages/metrics/metrics_explorer/hooks/use_metrics_explorer_options';
import {
MetricsExplorerOptions,
MetricsExplorerTimestampsRT,
} from '../../../pages/metrics/metrics_explorer/hooks/use_metrics_explorer_options';
import { useMetricsExplorerData } from '../../../pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data';
import { MetricExplorerCustomMetricAggregations } from '../../../../common/http_api/metrics_explorer';

Expand Down Expand Up @@ -52,23 +56,19 @@ export const useMetricsExplorerChartData = (
groupBy,
]
);
const timerange = useMemo(
() => ({
const timestamps: MetricsExplorerTimestampsRT = useMemo(() => {
const from = `now-${(timeSize || 1) * 20}${timeUnit}`;
const to = 'now';
const fromTimestamp = DateMath.parse(from)!.valueOf();
const toTimestamp = DateMath.parse(to, { roundUp: true })!.valueOf();
return {
interval: `>=${timeSize || 1}${timeUnit}`,
from: `now-${(timeSize || 1) * 20}${timeUnit}`,
to: 'now',
}),
[timeSize, timeUnit]
);
fromTimestamp,
toTimestamp,
};
}, [timeSize, timeUnit]);

return useMetricsExplorerData(
options,
source?.configuration,
derivedIndexPattern,
timerange,
null,
null
);
return useMetricsExplorerData(options, source?.configuration, derivedIndexPattern, timestamps);
};

const mapMetricThresholdMetricToMetricsExplorerMetric = (metric: MetricExpressionCustomMetric) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const WithMetricsExplorerOptionsUrlState = () => {
options,
chartOptions,
setChartOptions,
currentTimerange,
timeRange,
setOptions: setRawOptions,
setTimeRange,
} = useMetricsExplorerOptionsContainerContext();
Expand All @@ -43,9 +43,9 @@ export const WithMetricsExplorerOptionsUrlState = () => {
() => ({
options,
chartOptions,
timerange: currentTimerange,
timerange: timeRange,
}),
[options, chartOptions, currentTimerange]
[options, chartOptions, timeRange]
);

const handleChange = (newUrlState: MetricsExplorerUrlState | undefined) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
* 2.0.
*/

import moment from 'moment-timezone';
import { useUiSetting$ } from '@kbn/kibana-react-plugin/public';
import { UI_SETTINGS } from '@kbn/data-plugin/public';

export function useKibanaTimeZoneSetting() {
const [kibanaTimeZone] = useUiSetting$<string>(UI_SETTINGS.DATEFORMAT_TZ);

if (!kibanaTimeZone || kibanaTimeZone === 'Browser') {
return 'local';
return moment.tz.guess();
simianhacker marked this conversation as resolved.
Show resolved Hide resolved
}

return kibanaTimeZone;
Expand Down
114 changes: 61 additions & 53 deletions x-pack/plugins/infra/public/pages/metrics/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { i18n } from '@kbn/i18n';
import React, { useContext } from 'react';
import { RouteComponentProps, Switch } from 'react-router-dom';
import { Route } from '@kbn/shared-ux-router';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

import { EuiErrorBoundary, EuiHeaderLinks, EuiHeaderLink } from '@elastic/eui';
import { useKibana } from '@kbn/kibana-react-plugin/public';
Expand Down Expand Up @@ -52,6 +54,7 @@ const ADD_DATA_LABEL = i18n.translate('xpack.infra.metricsHeaderAddDataButtonLab
export const InfrastructurePage = ({ match }: RouteComponentProps) => {
const uiCapabilities = useKibana().services.application?.capabilities;
const { setHeaderActionMenu, theme$ } = useContext(HeaderActionMenuContext);
const queryClient = new QueryClient();

const settingsTabTitle = i18n.translate('xpack.infra.metrics.settingsTabTitle', {
defaultMessage: 'Settings',
Expand All @@ -73,60 +76,65 @@ export const InfrastructurePage = ({ match }: RouteComponentProps) => {
<WaffleOptionsProvider>
<WaffleTimeProvider>
<WaffleFiltersProvider>
<InfraMLCapabilitiesProvider>
<HelpCenterContent
feedbackLink="https://discuss.elastic.co/c/metrics"
appName={i18n.translate('xpack.infra.header.infrastructureHelpAppName', {
defaultMessage: 'Metrics',
})}
/>

{setHeaderActionMenu && theme$ && (
<HeaderMenuPortal setHeaderActionMenu={setHeaderActionMenu} theme$={theme$}>
<EuiHeaderLinks gutterSize="xs">
<EuiHeaderLink color={'text'} {...settingsLinkProps}>
{settingsTabTitle}
</EuiHeaderLink>
<Route path={'/inventory'} component={AnomalyDetectionFlyout} />
<MetricsAlertDropdown />
<EuiHeaderLink
href={kibana.services?.application?.getUrlForApp('/integrations/browse')}
color="primary"
iconType="indexOpen"
>
{ADD_DATA_LABEL}
</EuiHeaderLink>
</EuiHeaderLinks>
</HeaderMenuPortal>
)}
<Switch>
<Route path={'/inventory'} component={SnapshotPage} />
<Route
path={'/explorer'}
render={(props) => (
<WithSource>
{({ configuration, createDerivedIndexPattern }) => (
<MetricsExplorerOptionsContainer>
<WithMetricsExplorerOptionsUrlState />
{configuration ? (
<PageContent
configuration={configuration}
createDerivedIndexPattern={createDerivedIndexPattern}
/>
) : (
<SourceLoadingPage />
)}
</MetricsExplorerOptionsContainer>
)}
</WithSource>
)}
<QueryClientProvider client={queryClient}>
<ReactQueryDevtools initialIsOpen={false} />
simianhacker marked this conversation as resolved.
Show resolved Hide resolved
<InfraMLCapabilitiesProvider>
<HelpCenterContent
feedbackLink="https://discuss.elastic.co/c/metrics"
appName={i18n.translate('xpack.infra.header.infrastructureHelpAppName', {
defaultMessage: 'Metrics',
})}
/>
<Route path="/detail/:type/:node" component={MetricDetail} />
<Route path={'/hosts'} component={HostsLandingPage} />
<Route path={'/settings'} component={MetricsSettingsPage} />
<Route render={() => <NotFoundPage title="Infrastructure" />} />
</Switch>
</InfraMLCapabilitiesProvider>

{setHeaderActionMenu && theme$ && (
<HeaderMenuPortal setHeaderActionMenu={setHeaderActionMenu} theme$={theme$}>
<EuiHeaderLinks gutterSize="xs">
<EuiHeaderLink color={'text'} {...settingsLinkProps}>
{settingsTabTitle}
</EuiHeaderLink>
<Route path={'/inventory'} component={AnomalyDetectionFlyout} />
<MetricsAlertDropdown />
<EuiHeaderLink
href={kibana.services?.application?.getUrlForApp(
'/integrations/browse'
)}
color="primary"
iconType="indexOpen"
>
{ADD_DATA_LABEL}
</EuiHeaderLink>
</EuiHeaderLinks>
</HeaderMenuPortal>
)}
<Switch>
<Route path={'/inventory'} component={SnapshotPage} />
<Route
path={'/explorer'}
render={(props) => (
<WithSource>
{({ configuration, createDerivedIndexPattern }) => (
<MetricsExplorerOptionsContainer>
<WithMetricsExplorerOptionsUrlState />
{configuration ? (
<PageContent
configuration={configuration}
createDerivedIndexPattern={createDerivedIndexPattern}
/>
) : (
<SourceLoadingPage />
)}
</MetricsExplorerOptionsContainer>
)}
</WithSource>
)}
/>
<Route path="/detail/:type/:node" component={MetricDetail} />
<Route path={'/hosts'} component={HostsLandingPage} />
<Route path={'/settings'} component={MetricsSettingsPage} />
<Route render={() => <NotFoundPage title="Infrastructure" />} />
</Switch>
</InfraMLCapabilitiesProvider>
</QueryClientProvider>
</WaffleFiltersProvider>
</WaffleTimeProvider>
</WaffleOptionsProvider>
Expand Down
Loading