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

[WIP] - Improve performance #212173

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -67,28 +67,30 @@ export const getFieldItemsData = ({
selectedCategoryIds.length > 0 ? selectedCategoryIds : Object.keys(browserFields);
const selectedFieldIds = new Set(columnIds);

const fieldItems = uniqBy(
'name',
categoryIds.reduce<BrowserFieldItem[]>((fieldItemsAcc, categoryId) => {
const getFieldItems = () => {
let fieldItemsAcc: BrowserFieldItem[] = [];
for (let i = 0; i < categoryIds.length; i += 1) {
const categoryId = categoryIds[i];
const categoryBrowserFields = Object.values(browserFields[categoryId]?.fields ?? {});
if (categoryBrowserFields.length > 0) {
fieldItemsAcc.push(
Copy link
Contributor Author

@michaelolo24 michaelolo24 Feb 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At scale this was crashing the browser (tested with 500k fields):
Screenshot 2025-02-22 at 12 47 53 AM

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Screenshot 2025-02-22 at 12 47 59 AM

...categoryBrowserFields.map(({ name = '', ...field }) => {
return {
name,
type: field.type,
description: getDescription(name, EcsFlat as Record<string, EcsMetadata>),
example: field.example?.toString(),
category: getCategory(name),
selected: selectedFieldIds.has(name),
isRuntime: !!field.runtimeField,
};
})
);
const categoryFieldItems = categoryBrowserFields.map(({ name = '', ...field }) => {
return {
name,
type: field.type,
description: getDescription(name, EcsFlat as Record<string, EcsMetadata>),
example: field.example?.toString(),
category: getCategory(name),
selected: selectedFieldIds.has(name),
isRuntime: !!field.runtimeField,
};
});
fieldItemsAcc = fieldItemsAcc.concat(categoryFieldItems);
}
return fieldItemsAcc;
}, [])
);
}
return fieldItemsAcc;
};

const fieldItems = uniqBy('name', getFieldItems());
return { fieldItems };
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
SecurityCellActionType,
} from '../cell_actions';
import { getSourcererScopeId } from '../../../helpers';
import { TimelineContext } from '../../../timelines/components/timeline';
import { TimelineContext } from '../../../timelines/components/timeline/context';

import { TableContext } from '../events_viewer/shared';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import React from 'react';
import React, { useMemo } from 'react';
import type { FC } from 'react';
import type { KibanaPageTemplateProps } from '@kbn/shared-ux-page-kibana-template';
import { useKibana } from '../../lib/kibana';
Expand All @@ -15,14 +15,18 @@ import { useKibana } from '../../lib/kibana';
*
* The `template` prop can be used to alter the page layout for a given plugin route / all routes within a plugin - depending on the nesting.
*/
export const PluginTemplateWrapper: FC<KibanaPageTemplateProps> = ({ children, ...rest }) => {
const {
services: {
securityLayout: { getPluginWrapper },
},
} = useKibana();
export const PluginTemplateWrapper: FC<KibanaPageTemplateProps> = React.memo(
Copy link
Contributor Author

@michaelolo24 michaelolo24 Feb 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prevent multiple re-renders of the UI due to reference changes

({ children, ...rest }) => {
const {
services: {
securityLayout: { getPluginWrapper },
},
} = useKibana();

const Wrapper = getPluginWrapper();
const Wrapper = useMemo(() => getPluginWrapper(), [getPluginWrapper]);

return <Wrapper {...rest}>{children}</Wrapper>;
};
return <Wrapper {...rest}>{children}</Wrapper>;
}
);

PluginTemplateWrapper.displayName = 'PluginTemplateWrapper';
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ import type { ENDPOINT_FIELDS_SEARCH_STRATEGY } from '../../../../common/endpoin
export type { BrowserFields };

export function getAllBrowserFields(browserFields: BrowserFields): Array<Partial<FieldSpec>> {
const result: Array<Partial<FieldSpec>> = [];
let result: Array<Partial<FieldSpec>> = [];
for (const namespace of Object.values(browserFields)) {
if (namespace.fields) {
result.push(...Object.values(namespace.fields));
const namespaceFields = Object.values(namespace.fields);
result = result.concat(namespaceFields);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}
}
return result;
Expand All @@ -36,9 +37,11 @@ export function getAllBrowserFields(browserFields: BrowserFields): Array<Partial
* @param browserFields
* @returns
*/
export const getAllFieldsByName = (
browserFields: BrowserFields
): { [fieldName: string]: Partial<FieldSpec> } => keyBy('name', getAllBrowserFields(browserFields));
export const getAllFieldsByName = memoizeOne(
(browserFields: BrowserFields): { [fieldName: string]: Partial<FieldSpec> } =>
keyBy('name', getAllBrowserFields(browserFields)),
(newArgs, lastArgs) => newArgs[0] === lastArgs[0]
);

export const getIndexFields = memoizeOne(
(title: string, fields: IIndexPatternFieldList): DataViewBase =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import type { ConnectedProps } from 'react-redux';
import { connect, useDispatch } from 'react-redux';
import type { Dispatch } from 'redux';
import { isTab } from '@kbn/timelines-plugin/public';
import type { Filter } from '@kbn/es-query';
import type { Filter, TimeRange } from '@kbn/es-query';
import type { DocLinks } from '@kbn/doc-links';
import {
dataTableActions,
Expand Down Expand Up @@ -299,22 +299,13 @@ const DetectionEnginePageComponent: React.FC<DetectionEngineComponentProps> = ()
[isLoadingIndexPattern, areDetectionPageFiltersLoading]
);

const AlertPageFilters = useMemo(
() => (
<DetectionEngineFilters
filters={topLevelFilters}
onFiltersChange={onFilterControlsChange}
query={query}
timeRange={{
from,
to,
mode: 'absolute',
}}
onInit={setDetectionPageFilterHandler}
dataViewSpec={sourcererDataView}
/>
),
[from, sourcererDataView, onFilterControlsChange, query, to, topLevelFilters]
const pageFiltersTimerange = useMemo<TimeRange>(
() => ({
from,
to,
mode: 'absolute',
}),
[from, to]
);

const renderAlertTable = useCallback(
Expand Down Expand Up @@ -408,7 +399,14 @@ const DetectionEnginePageComponent: React.FC<DetectionEngineComponentProps> = ()
</HeaderPage>
<EuiHorizontalRule margin="none" />
<EuiSpacer size="l" />
{AlertPageFilters}
<DetectionEngineFilters
filters={topLevelFilters}
onFiltersChange={onFilterControlsChange}
query={query}
timeRange={pageFiltersTimerange}
onInit={setDetectionPageFilterHandler}
dataViewSpec={sourcererDataView}
/>
<EuiSpacer size="l" />
<ChartPanels
addFilter={addFilter}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ export const useSourcererDataView = (
);

const [legacyPatterns, setLegacyPatterns] = useState<string[]>([]);

const [indexPatternsLoading, fetchIndexReturn] = useFetchIndex(legacyPatterns);

const legacyDataView: Omit<SourcererDataView, 'id'> & { id: string | null } = useMemo(
Expand All @@ -67,10 +66,10 @@ export const useSourcererDataView = (
if (selectedDataView == null || missingPatterns.length > 0) {
// old way of fetching indices, legacy timeline
setLegacyPatterns(selectedPatterns);
} else {
} else if (legacyPatterns.length > 0) {
Copy link
Contributor Author

@michaelolo24 michaelolo24 Feb 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A new [] was being created on every run of this hook, thereby updating state, thereby re-rendering every component where this hook is being called when this state updated. Only create a new empty array reference, if legacyPatterns was ever set.

setLegacyPatterns([]);
}
}, [missingPatterns, selectedDataView, selectedPatterns]);
}, [legacyPatterns.length, missingPatterns, selectedDataView, selectedPatterns]);

const sourcererDataView = useMemo(() => {
const _dv =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import React, { useContext, useMemo } from 'react';
import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui';
import { css } from '@emotion/css';
import classNames from 'classnames';
import { TimelineContext } from '../../timeline';
import { TimelineContext } from '../../timeline/context';
import { getSourcererScopeId } from '../../../../helpers';
import { escapeDataProviderId } from '../../../../common/components/drag_and_drop/helpers';
import { defaultToEmptyTag } from '../../../../common/components/empty_value';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@
import type { ComponentProps, ReactElement } from 'react';
import React, { useMemo } from 'react';
import { RootDragDropProvider } from '@kbn/dom-drag-drop';
import { useGetScopedSourcererDataView } from '../../../../sourcerer/components/use_get_sourcerer_data_view';
import { DataViewErrorComponent } from '../../../../common/components/with_data_view/data_view_error';
import { StyledTableFlexGroup, StyledUnifiedTableFlexItem } from '../unified_components/styles';
import { UnifiedTimeline } from '../unified_components';
import { defaultUdtHeaders } from './column_headers/default_headers';
import { SourcererScopeName } from '../../../../sourcerer/store/model';

export interface UnifiedTimelineBodyProps extends ComponentProps<typeof UnifiedTimeline> {
header: ReactElement;
}

export const UnifiedTimelineBody = (props: UnifiedTimelineBodyProps) => {
export const UnifiedTimelineBody = (props: Omit<UnifiedTimelineBodyProps, 'dataView'>) => {
const {
header,
isSortEnabled,
Expand All @@ -37,7 +40,9 @@ export const UnifiedTimelineBody = (props: UnifiedTimelineBodyProps) => {
leadingControlColumns,
onUpdatePageIndex,
} = props;

const dataView = useGetScopedSourcererDataView({
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed withDataView in favor of this call as it only happens in one place in the tree since the only other location it was used was the child component UnifiedTimeline here

sourcererScope: SourcererScopeName.timeline,
});
const columnsHeader = useMemo(() => columns ?? defaultUdtHeaders, [columns]);

return (
Expand All @@ -48,26 +53,31 @@ export const UnifiedTimelineBody = (props: UnifiedTimelineBodyProps) => {
data-test-subj="unifiedTimelineBody"
>
<RootDragDropProvider>
<UnifiedTimeline
columns={columnsHeader}
rowRenderers={rowRenderers}
isSortEnabled={isSortEnabled}
timelineId={timelineId}
itemsPerPage={itemsPerPage}
itemsPerPageOptions={itemsPerPageOptions}
sort={sort}
events={events}
refetch={refetch}
dataLoadingState={dataLoadingState}
totalCount={totalCount}
onFetchMoreRecords={onFetchMoreRecords}
activeTab={activeTab}
updatedAt={updatedAt}
isTextBasedQuery={false}
trailingControlColumns={trailingControlColumns}
leadingControlColumns={leadingControlColumns}
onUpdatePageIndex={onUpdatePageIndex}
/>
{dataView ? (
<UnifiedTimeline
columns={columnsHeader}
dataView={dataView}
rowRenderers={rowRenderers}
isSortEnabled={isSortEnabled}
timelineId={timelineId}
itemsPerPage={itemsPerPage}
itemsPerPageOptions={itemsPerPageOptions}
sort={sort}
events={events}
refetch={refetch}
dataLoadingState={dataLoadingState}
totalCount={totalCount}
onFetchMoreRecords={onFetchMoreRecords}
activeTab={activeTab}
updatedAt={updatedAt}
isTextBasedQuery={false}
trailingControlColumns={trailingControlColumns}
leadingControlColumns={leadingControlColumns}
onUpdatePageIndex={onUpdatePageIndex}
/>
) : (
<DataViewErrorComponent />
)}
</RootDragDropProvider>
</StyledUnifiedTableFlexItem>
</StyledTableFlexGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { createContext } from 'react';

export const TimelineContext = createContext<{
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor code re-organization

timelineId: string | null;
}>({ timelineId: null });
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { pick } from 'lodash/fp';
import { EuiPanel, EuiProgress, EuiText } from '@elastic/eui';
import React, { useCallback, useEffect, useMemo, useRef, createContext } from 'react';
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import styled from 'styled-components';

Expand All @@ -30,14 +30,14 @@ import { EXIT_FULL_SCREEN_CLASS_NAME } from '../../../common/components/exit_ful
import { useResolveConflict } from '../../../common/hooks/use_resolve_conflict';
import { sourcererSelectors } from '../../../common/store';
import { defaultUdtHeaders } from './body/column_headers/default_headers';
import { TimelineContext } from './context';

const TimelineBody = styled.div`
height: 100%;
display: flex;
flex-direction: column;
`;

export const TimelineContext = createContext<{ timelineId: string | null }>({ timelineId: null });
export interface Props {
renderCellValue: (props: CellValueElementProps) => React.ReactNode;
rowRenderers: RowRenderer[];
Expand Down
Loading