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

[Backport main] Bugfix/metric-loading-loop (#1309) #1318

Merged
merged 1 commit into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
44 changes: 27 additions & 17 deletions public/components/custom_panels/helpers/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,21 @@
* SPDX-License-Identifier: Apache-2.0
*/

import { ShortDate } from '@elastic/eui';

Check failure on line 6 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'ShortDate' is defined but never used

Check failure on line 6 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'ShortDate' is defined but never used
import { DurationRange } from '@elastic/eui/src/components/date_picker/types';

Check failure on line 7 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'DurationRange' is defined but never used

Check failure on line 7 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unable to resolve path to module '@elastic/eui/src/components/date_picker/types'

Check failure on line 7 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'DurationRange' is defined but never used

Check failure on line 7 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unable to resolve path to module '@elastic/eui/src/components/date_picker/types'
import _, { forEach, isEmpty, min } from 'lodash';
import { Moment } from 'moment-timezone';

Check failure on line 9 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'Moment' is defined but never used

Check failure on line 9 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'Moment' is defined but never used
import React from 'react';
import { Layout } from 'react-grid-layout';

Check failure on line 11 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'Layout' is defined but never used

Check failure on line 11 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'Layout' is defined but never used
import { CoreStart } from '../../../../../../src/core/public';

Check failure on line 12 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'CoreStart' is defined but never used

Check failure on line 12 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'CoreStart' is defined but never used
import { PPL_INDEX_REGEX, PPL_WHERE_CLAUSE_REGEX } from '../../../../common/constants/shared';
import { QueryManager } from '../../../../common/query_manager';
import {
SavedVisualizationType,

Check failure on line 16 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'SavedVisualizationType' is defined but never used

Check failure on line 16 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'SavedVisualizationType' is defined but never used
VisualizationType,

Check failure on line 17 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'VisualizationType' is defined but never used

Check failure on line 17 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'VisualizationType' is defined but never used
VizContainerError,

Check failure on line 18 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'VizContainerError' is defined but never used

Check failure on line 18 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'VizContainerError' is defined but never used
} from '../../../../common/types/custom_panels';
import { SavedVisualization } from '../../../../common/types/explorer';

Check failure on line 20 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'SavedVisualization' is defined but never used

Check failure on line 20 in public/components/custom_panels/helpers/utils.tsx

View workflow job for this annotation

GitHub Actions / Lint

'SavedVisualization' is defined but never used
import { removeBacktick } from '../../../../common/utils';
import { getVizContainerProps } from '../../../components/visualizations/charts/helpers';
import PPLService from '../../../services/requests/ppl';
Expand Down Expand Up @@ -259,25 +259,34 @@
};
};

const createCatalogVisualizationMetaData = (
catalogSource: string,
visualizationQuery: string,
visualizationType: string,
visualizationTimeField: string,
queryData: object
) => {
const createCatalogVisualizationMetaData = ({
catalogSource,
query,
type,
subType,
timeField,
queryData,
}: {
catalogSource: string;
query: string;
type: string;
subType: string;
timeField: string;
queryData: object;
}) => {

Check warning on line 276 in public/components/custom_panels/helpers/utils.tsx

View check run for this annotation

Codecov / codecov/patch

public/components/custom_panels/helpers/utils.tsx#L276

Added line #L276 was not covered by tests
return {
name: catalogSource,
description: '',
query: visualizationQuery,
type: visualizationType,
query,
type,
subType,
selected_date_range: {
start: 'now/y',
end: 'now',
text: '',
},
selected_timestamp: {
name: visualizationTimeField,
name: timeField,
type: 'timestamp',
},
selected_fields: {
Expand Down Expand Up @@ -332,6 +341,7 @@

const visualizationType = 'line';
const visualizationTimeField = '@timestamp';
const visualizationSubType = visualization.subType;

Check warning on line 344 in public/components/custom_panels/helpers/utils.tsx

View check run for this annotation

Codecov / codecov/patch

public/components/custom_panels/helpers/utils.tsx#L344

Added line #L344 was not covered by tests

const visualizationQuery = updateCatalogVisualizationQuery({
...visualization.queryMetaData,
Expand All @@ -357,15 +367,15 @@
);
setVisualizationData(queryData);

const visualizationMetaData = createCatalogVisualizationMetaData(
const visualizationMetaData = createCatalogVisualizationMetaData({

Check warning on line 370 in public/components/custom_panels/helpers/utils.tsx

View check run for this annotation

Codecov / codecov/patch

public/components/custom_panels/helpers/utils.tsx#L370

Added line #L370 was not covered by tests
catalogSource,
visualizationQuery,
visualizationType,
visualizationTimeField,
queryData
);
query: visualizationQuery,
type: visualizationType,
subType: visualization.subType,
timeField: visualizationTimeField,
queryData,
});

console.log('renderCatalogVisualization', { visualizationMetaData });
setVisualizationMetaData(visualizationMetaData);
} catch (error) {
setIsError({ error });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@
import { VizContainerError } from '../../../../../common/types/custom_panels';
import { metricQuerySelector } from '../../../metrics/redux/slices/metrics_slice';
import { coreRefs } from '../../../../framework/core_refs';
import { PROMQL_METRIC_SUBTYPE } from '../../../../../common/constants/shared';
import {
PROMQL_METRIC_SUBTYPE,
observabilityMetricsID,
} from '../../../../../common/constants/shared';

/*
* Visualization container - This module is a placeholder to add visualizations in react-grid-layout
Expand Down Expand Up @@ -78,6 +81,7 @@
removeVisualization?: (visualizationId: string) => void;
catalogVisualization?: boolean;
inlineEditor?: JSX.Element;
actionMenuType?: string;
}

export const VisualizationContainer = ({
Expand All @@ -98,6 +102,7 @@
removeVisualization,
catalogVisualization,
inlineEditor,
actionMenuType,
}: Props) => {
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
const [visualizationTitle, setVisualizationTitle] = useState('');
Expand Down Expand Up @@ -175,7 +180,11 @@
disabled={editMode}
onClick={() => {
closeActionsMenu();
onEditClick(savedVisualizationId);
if (visualizationMetaData?.subType === PROMQL_METRIC_SUBTYPE) {
window.location.assign(`${observabilityMetricsID}#/${savedVisualizationId}`);
} else {
onEditClick(savedVisualizationId);

Check warning on line 186 in public/components/custom_panels/panel_modules/visualization_container/visualization_container.tsx

View check run for this annotation

Codecov / codecov/patch

public/components/custom_panels/panel_modules/visualization_container/visualization_container.tsx#L184-L186

Added lines #L184 - L186 were not covered by tests
}
}}
>
Edit
Expand Down Expand Up @@ -217,7 +226,10 @@
</EuiContextMenuItem>,
];

if (visualizationMetaData?.subType === PROMQL_METRIC_SUBTYPE) {
if (
visualizationMetaData?.subType === PROMQL_METRIC_SUBTYPE &&
actionMenuType === 'metricsGrid'

Check warning on line 231 in public/components/custom_panels/panel_modules/visualization_container/visualization_container.tsx

View check run for this annotation

Codecov / codecov/patch

public/components/custom_panels/panel_modules/visualization_container/visualization_container.tsx#L231

Added line #L231 was not covered by tests
) {
popoverPanel = [showPPLQueryPanel];
} else if (usedInNotebooks) {
popoverPanel = [popoverPanel[0]];
Expand Down Expand Up @@ -304,12 +316,12 @@
)}
</div>
),
[onRefresh, isLoading, isError, visualizationData, visualizationType, visualizationMetaData]

Check warning on line 319 in public/components/custom_panels/panel_modules/visualization_container/visualization_container.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useMemo has a missing dependency: 'showModal'. Either include it or remove the dependency array

Check warning on line 319 in public/components/custom_panels/panel_modules/visualization_container/visualization_container.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useMemo has a missing dependency: 'showModal'. Either include it or remove the dependency array
);

useEffect(() => {
loadVisaulization();
}, [onRefresh, inputMetaData, span, resolution, fromTime, toTime]);

Check warning on line 324 in public/components/custom_panels/panel_modules/visualization_container/visualization_container.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'loadVisaulization'. Either include it or remove the dependency array

Check warning on line 324 in public/components/custom_panels/panel_modules/visualization_container/visualization_container.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'loadVisaulization'. Either include it or remove the dependency array

const metricVisCssClassName = catalogVisualization ? 'metricVis' : '';

Expand Down
48 changes: 24 additions & 24 deletions public/components/metrics/redux/slices/metrics_slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
* SPDX-License-Identifier: Apache-2.0
*/

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { keyBy, mergeWith, pick, sortBy, merge } from 'lodash';
import { createSlice } from '@reduxjs/toolkit';
import { keyBy, mergeWith, pick, sortBy } from 'lodash';
import { ouiPaletteColorBlindBehindText } from '@elastic/eui';
import {
OBSERVABILITY_CUSTOM_METRIC,
Expand All @@ -18,7 +18,7 @@ import { ObservabilitySavedVisualization } from '../../../../services/saved_obje
import { pplServiceRequestor } from '../../helpers/utils';
import { coreRefs } from '../../../../framework/core_refs';
import { PPL_METRIC_SUBTYPE, PROMQL_METRIC_SUBTYPE } from '../../../../../common/constants/shared';
import { getOSDHttp, getPPLService } from '../../../../../common/utils';
import { getPPLService } from '../../../../../common/utils';

export interface IconAttributes {
color: string;
Expand All @@ -38,6 +38,14 @@ const coloredIconsFrom = (dataSources: string[]): { [dataSource: string]: IconAt
return Object.fromEntries(keyedIcons);
};

export interface DateSpanFilter {
start: string;
end: string;
span: number;
resolution: string;
recentlyUsedRanges: string[];
}

const initialState = {
metrics: {},
selectedIds: [],
Expand Down Expand Up @@ -66,8 +74,13 @@ const mergeMetricCustomizer = function (objValue, srcValue) {
: srcValue.availableAttributes,
};
};
export const mergeMetrics = (newMetricMap) => (dispatch, getState) => {
const { metrics } = getState().metrics;
const modifiableMetricsMap = { ...metrics };

const now = () => new Date().getMilliseconds();
const mergedMetrics = mergeWith(modifiableMetricsMap, newMetricMap, mergeMetricCustomizer);
dispatch(setMetrics(mergedMetrics));
};

export const loadMetrics = () => async (dispatch) => {
const pplService = getPPLService();
Expand All @@ -81,15 +94,15 @@ export const loadMetrics = () => async (dispatch) => {
setDataSourceIcons(coloredIconsFrom([OBSERVABILITY_CUSTOM_METRIC, ...remoteDataSources]))
);

const remoteDataRequests = fetchRemoteMetrics(remoteDataSources);
const remoteDataRequests = await fetchRemoteMetrics(remoteDataSources);
const metricsResultSet = await Promise.all([customDataRequest, ...remoteDataRequests]);
const metricsResult = metricsResultSet.flat();

const metricsMapById = keyBy(metricsResult.flat(), 'id');
await dispatch(mergeMetrics(metricsMapById));
dispatch(mergeMetrics(metricsMapById));

const sortedIds = sortBy(metricsResult, 'catalog', 'id').map((m) => m.id);
await dispatch(setSortedIds(sortedIds));
dispatch(setSortedIds(sortedIds));
};

const fetchCustomMetrics = async () => {
Expand Down Expand Up @@ -150,17 +163,9 @@ export const metricSlice = createSlice({
name: REDUX_SLICE_METRICS,
initialState,
reducers: {
mergeMetrics: (state, { payload }) => {
const { metrics } = state;
const modifiableMetricsMap = { ...metrics };

const mergedMetrics = mergeWith(modifiableMetricsMap, payload, mergeMetricCustomizer);
state.metrics = mergedMetrics;
setMetrics: (state, { payload }) => {
state.metrics = payload;
},

// setMetrics: (state, { payload }) => {
// state.metrics = payload;
// },
setMetric: (state, { payload }) => {
state.metrics[payload.id] = payload;
},
Expand Down Expand Up @@ -214,8 +219,7 @@ export const metricSlice = createSlice({
export const {
deSelectMetric,
clearSelectedMetrics,

mergeMetrics,
selectMetric,
moveMetric,
setSearch,
setDateSpan,
Expand All @@ -227,7 +231,7 @@ export const {

/** private actions */

const { selectMetric, setMetric, setSortedIds } = metricSlice.actions;
const { setMetrics, setMetric, setSortedIds } = metricSlice.actions;

const getAvailableAttributes = (id, metricIndex) => async (dispatch, getState) => {
const { toasts } = coreRefs;
Expand Down Expand Up @@ -300,16 +304,12 @@ export const availableMetricsSelector = (state) => {
export const selectedMetricsSelector = (state) =>
pick(state.metrics.metrics, state.metrics.selectedIds) ?? {};

export const selectedMetricByIdSelector = (id) => (state) => state.metrics.metrics[id];

export const selectedMetricsIdsSelector = (state) => state.metrics.selectedIds ?? [];

export const searchSelector = (state) => state.metrics.search;

export const metricIconsSelector = (state) => state.metrics.dataSourceIcons;

export const metricsLayoutSelector = (state) => state.metrics.metricsLayout;

export const dateSpanFilterSelector = (state) => state.metrics.dateSpanFilter;

export const refreshSelector = (state) => state.metrics.refresh;
Expand Down
8 changes: 5 additions & 3 deletions public/components/metrics/sidebar/sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,12 @@

useEffect(() => {
if (additionalMetric) {
dispatch(clearSelectedMetrics());
dispatch(addSelectedMetric(additionalMetric));
(async function () {
await dispatch(clearSelectedMetrics());
await dispatch(addSelectedMetric(additionalMetric));

Check warning on line 48 in public/components/metrics/sidebar/sidebar.tsx

View check run for this annotation

Codecov / codecov/patch

public/components/metrics/sidebar/sidebar.tsx#L46-L48

Added lines #L46 - L48 were not covered by tests
})();
}
}, [additionalMetric]);
}, [additionalMetric?.id]);

Check warning on line 51 in public/components/metrics/sidebar/sidebar.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has missing dependencies: 'additionalMetric' and 'dispatch'. Either include them or remove the dependency array

Check warning on line 51 in public/components/metrics/sidebar/sidebar.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has missing dependencies: 'additionalMetric' and 'dispatch'. Either include them or remove the dependency array

const selectedMetricsList = useMemo(() => {
return selectedMetricsIds.map((id) => selectedMetrics[id]).filter((m) => m); // filter away null entries
Expand Down
16 changes: 15 additions & 1 deletion public/components/metrics/view/metrics_grid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*/

import React, { useEffect, useMemo } from 'react';
import { EuiDragDropContext, EuiDraggable, EuiDroppable } from '@elastic/eui';
import { EuiContextMenuItem, EuiDragDropContext, EuiDraggable, EuiDroppable } from '@elastic/eui';
import { useObservable } from 'react-use';
import { connect } from 'react-redux';
import { CoreStart } from '../../../../../../src/core/public';
Expand Down Expand Up @@ -53,6 +53,19 @@
},
});

const promQLActionMenu = [
<EuiContextMenuItem
data-test-subj="showCatalogPPLQuery"
key="view_query"
onClick={() => {
closeActionsMenu();
showModal('catalogModal');

Check warning on line 62 in public/components/metrics/view/metrics_grid.tsx

View check run for this annotation

Codecov / codecov/patch

public/components/metrics/view/metrics_grid.tsx#L60-L62

Added lines #L60 - L62 were not covered by tests
}}
>
View query
</EuiContextMenuItem>,
];

const navigateToEventExplorerVisualization = (savedVisualizationId: string) => {
window.location.assign(`${observabilityLogsID}#/explorer/${savedVisualizationId}`);
};
Expand Down Expand Up @@ -80,6 +93,7 @@
inlineEditor={
metric.subType === PROMQL_METRIC_SUBTYPE && <MetricsEditInline visualization={metric} />
}
actionMenuType="metricsGrid"
/>
</EuiDraggable>
);
Expand Down Expand Up @@ -117,7 +131,7 @@
/>
);
});
}, [selectedMetrics, dateSpanFilter]);

Check warning on line 134 in public/components/metrics/view/metrics_grid.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useMemo has missing dependencies: 'allMetrics' and 'selectedMetricsIds'. Either include them or remove the dependency array

Check warning on line 134 in public/components/metrics/view/metrics_grid.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useMemo has missing dependencies: 'allMetrics' and 'selectedMetricsIds'. Either include them or remove the dependency array

// Reset Size of Panel Grid when Nav Dock is Locked
useEffect(() => {
Expand Down
2 changes: 1 addition & 1 deletion public/services/requests/ppl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { PPL_BASE, PPL_SEARCH } from '../../../common/constants/shared';
/* eslint-disable import/no-default-export */
export default class PPLService {
private http;

constructor(http: CoreStart['http']) {
this.http = http;
}
Expand All @@ -20,7 +21,6 @@ export default class PPLService {
},
errorHandler?: (error: any) => void
) => {
console.log('real fetch');
return this.http
.post(`${PPL_BASE}${PPL_SEARCH}`, {
body: JSON.stringify(params),
Expand Down
Loading