Skip to content

Commit

Permalink
[ML] Refactors Field statistics table from an embeddable to a registe…
Browse files Browse the repository at this point in the history
…red React component (#181502)

## Summary

Addresses #174965. This PR
refactors Field statistics table from an embeddable to a async React
component.

**Context**
Initially when embeddable was implemented, we could not register
dataVisualizer as an optional plugin due to the cyclical dependencies
and enforced package import rules (from x-pack to discover). However,
due to changes in the infrastructure in the last few years, we can now
register x-pack plugins as a dependency. This eliminates the need for an
embeddable as a wrapper around the field statistics table.

**Reviewer's note**
- Discover team: `dataVisualizer` plugin is now added as an optional
dependency in Discover
- Kibana Core team: `dataVisualizer` plugin is now added as an optional
dependency in Discover, `discover` removed from Data visualizer plugin


https://github.com/elastic/kibana/assets/43350163/7800291a-ad8c-447e-9bfc-e4f279b05d6a



https://github.com/elastic/kibana/assets/43350163/d7422e11-a0c7-4a8b-8f47-783e453f02a8

Follow up after this PR:
- #180849
- #181904

### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [x] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces—unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes—Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

---------

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
  • Loading branch information
qn895 and kibanamachine authored May 9, 2024
1 parent 9779b62 commit ea4d2c3
Show file tree
Hide file tree
Showing 47 changed files with 688 additions and 670 deletions.
1 change: 1 addition & 0 deletions src/plugins/discover/kibana.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"contentManagement"
],
"optionalPlugins": [
"dataVisualizer",
"home",
"share",
"usageCollection",
Expand Down
4 changes: 4 additions & 0 deletions src/plugins/discover/public/__mocks__/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { createDiscoverDataViewsMock } from './data_views';
import { SearchSourceDependencies } from '@kbn/data-plugin/common';
import { SearchResponse } from '@elastic/elasticsearch/lib/api/types';
import { urlTrackerMock } from './url_tracker.mock';
import { createElement } from 'react';

export function createDiscoverServicesMock(): DiscoverServices {
const dataPlugin = dataPluginMock.createStartContract();
Expand Down Expand Up @@ -152,6 +153,9 @@ export function createDiscoverServicesMock(): DiscoverServices {
},
getScopedHistory: () => scopedHistoryMock.create(),
data: dataPlugin,
dataVisualizer: {
FieldStatisticsTable: jest.fn(() => createElement('div')),
},
docLinks: docLinksServiceMock.createStartContract(),
capabilities: {
visualize: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

import React from 'react';
import { useQuerySubscriber } from '@kbn/unified-field-list/src/hooks/use_query_subscriber';
import { useSavedSearch } from '../../state_management/discover_state_provider';
import { FieldStatisticsTable, type FieldStatisticsTableProps } from './field_stats_table';
import { useDiscoverServices } from '../../../../hooks/use_discover_services';

Expand All @@ -18,12 +17,12 @@ export const FieldStatisticsTab: React.FC<Omit<FieldStatisticsTableProps, 'query
const querySubscriberResult = useQuerySubscriber({
data: services.data,
});
const savedSearch = useSavedSearch();

if (!services.dataVisualizer) return null;

return (
<FieldStatisticsTable
{...props}
savedSearch={savedSearch}
query={querySubscriberResult.query}
filters={querySubscriberResult.filters}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,109 +6,28 @@
* Side Public License, v 1.
*/

import React, { useEffect, useMemo, useRef, useState } from 'react';
import type { Filter, Query, AggregateQuery } from '@kbn/es-query';
import { METRIC_TYPE, UiCounterMetricType } from '@kbn/analytics';
import type { DataViewField, DataView } from '@kbn/data-views-plugin/public';
import {
EmbeddableInput,
EmbeddableOutput,
ErrorEmbeddable,
IEmbeddable,
isErrorEmbeddable,
} from '@kbn/embeddable-plugin/public';
import type { SavedSearch } from '@kbn/saved-search-plugin/public';
import React, { useEffect, useMemo, useCallback } from 'react';
import { METRIC_TYPE } from '@kbn/analytics';
import { EuiFlexItem } from '@elastic/eui';
import { css } from '@emotion/react';
import useObservable from 'react-use/lib/useObservable';
import { of } from 'rxjs';
import { of, map } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
import { useDiscoverServices } from '../../../../hooks/use_discover_services';
import { FIELD_STATISTICS_LOADED } from './constants';
import type { DiscoverStateContainer } from '../../state_management/discover_state';
export interface RandomSamplingOption {
mode: 'random_sampling';
seed: string;
probability: number;
}
import type { NormalSamplingOption, FieldStatisticsTableProps } from './types';
export type { FieldStatisticsTableProps };

export interface NormalSamplingOption {
mode: 'normal_sampling';
seed: string;
shardSize: number;
}
const statsTableCss = css({
width: '100%',
height: '100%',
overflowY: 'auto',
'.kbnDocTableWrapper': {
overflowX: 'hidden',
},
});

export interface NoSamplingOption {
mode: 'no_sampling';
seed: string;
}

export type SamplingOption = RandomSamplingOption | NormalSamplingOption | NoSamplingOption;

export interface DataVisualizerGridEmbeddableInput extends EmbeddableInput {
dataView: DataView;
savedSearch?: SavedSearch;
query?: Query | AggregateQuery;
visibleFieldNames?: string[];
filters?: Filter[];
showPreviewByDefault?: boolean;
/**
* Callback to add a filter to filter bar
*/
onAddFilter?: (field: DataViewField | string, value: string, type: '+' | '-') => void;
sessionId?: string;
fieldsToFetch?: string[];
totalDocuments?: number;
samplingOption?: SamplingOption;
}
export interface DataVisualizerGridEmbeddableOutput extends EmbeddableOutput {
showDistributions?: boolean;
}

export interface FieldStatisticsTableProps {
/**
* Determines which columns are displayed
*/
columns: string[];
/**
* The used data view
*/
dataView: DataView;
/**
* Saved search description
*/
searchDescription?: string;
/**
* Saved search title
*/
searchTitle?: string;
/**
* Optional saved search
*/
savedSearch?: SavedSearch;
/**
* Optional query to update the table content
*/
query?: Query | AggregateQuery;
/**
* Filters query to update the table content
*/
filters?: Filter[];
/**
* State container with persisted settings
*/
stateContainer?: DiscoverStateContainer;
/**
* Callback to add a filter to filter bar
*/
onAddFilter?: (field: DataViewField | string, value: string, type: '+' | '-') => void;
/**
* Metric tracking function
* @param metricType
* @param eventName
*/
trackUiMetric?: (metricType: UiCounterMetricType, eventName: string | string[]) => void;
searchSessionId?: string;
}
const fallBacklastReloadRequestTime$ = new BehaviorSubject(0);

export const FieldStatisticsTable = (props: FieldStatisticsTableProps) => {
const {
Expand All @@ -122,154 +41,69 @@ export const FieldStatisticsTable = (props: FieldStatisticsTableProps) => {
trackUiMetric,
searchSessionId,
} = props;

const totalHits = useObservable(stateContainer?.dataState.data$.totalHits$ ?? of(undefined));
const totalDocuments = useMemo(() => totalHits?.result, [totalHits]);

const services = useDiscoverServices();
const [embeddable, setEmbeddable] = useState<
| ErrorEmbeddable
| IEmbeddable<DataVisualizerGridEmbeddableInput, DataVisualizerGridEmbeddableOutput>
| undefined
>();
const embeddableRoot: React.RefObject<HTMLDivElement> = useRef<HTMLDivElement>(null);
const dataVisualizerService = services.dataVisualizer;

// State from Discover we want the embeddable to reflect
const showPreviewByDefault = useMemo(
() => (stateContainer ? !stateContainer.appState.getState().hideAggregatedPreview : true),
[stateContainer]
);

useEffect(() => {
const availableFields$ = stateContainer?.dataState.data$.availableFields$;
const sub = embeddable?.getOutput$().subscribe((output: DataVisualizerGridEmbeddableOutput) => {
if (output.showDistributions !== undefined && stateContainer) {
stateContainer.appState.update({ hideAggregatedPreview: !output.showDistributions });
}
});

const refetch = stateContainer?.dataState.refetch$.subscribe(() => {
if (embeddable && !isErrorEmbeddable(embeddable)) {
embeddable.updateInput({ lastReloadRequestTime: Date.now() });
}
});
const lastReloadRequestTime$ = useMemo(() => {
return stateContainer?.dataState?.refetch$
? stateContainer?.dataState?.refetch$.pipe(map(() => Date.now()))
: fallBacklastReloadRequestTime$;
}, [stateContainer]);

const fields = availableFields$?.subscribe(() => {
if (embeddable && !isErrorEmbeddable(embeddable) && !availableFields$?.getValue().error) {
embeddable.updateInput({ fieldsToFetch: availableFields$?.getValue().fields });
}
});

return () => {
sub?.unsubscribe();
refetch?.unsubscribe();
fields?.unsubscribe();
};
}, [embeddable, stateContainer]);

useEffect(() => {
if (embeddable && !isErrorEmbeddable(embeddable)) {
// Update embeddable whenever one of the important input changes
embeddable.updateInput({
dataView,
savedSearch,
query,
filters,
visibleFieldNames: columns,
onAddFilter,
sessionId: searchSessionId,
fieldsToFetch: stateContainer?.dataState.data$.availableFields$?.getValue().fields,
totalDocuments,
samplingOption: {
mode: 'normal_sampling',
shardSize: 5000,
seed: searchSessionId,
} as NormalSamplingOption,
});
embeddable.reload();
}
}, [
embeddable,
dataView,
savedSearch,
query,
columns,
filters,
onAddFilter,
searchSessionId,
totalDocuments,
stateContainer,
]);
const lastReloadRequestTime = useObservable(lastReloadRequestTime$, 0);

useEffect(() => {
if (showPreviewByDefault && embeddable && !isErrorEmbeddable(embeddable)) {
// Update embeddable whenever one of the important input changes
embeddable.updateInput({
showPreviewByDefault,
});

embeddable.reload();
}
}, [showPreviewByDefault, embeddable]);
// Track should only be called once when component is loaded
trackUiMetric?.(METRIC_TYPE.LOADED, FIELD_STATISTICS_LOADED);
}, [trackUiMetric]);

const samplingOption: NormalSamplingOption = useMemo(
() =>
({
mode: 'normal_sampling',
shardSize: 5000,
seed: searchSessionId,
} as NormalSamplingOption),
[searchSessionId]
);

useEffect(() => {
let unmounted = false;
const loadEmbeddable = async () => {
if (services.embeddable) {
const factory = services.embeddable.getEmbeddableFactory<
DataVisualizerGridEmbeddableInput,
DataVisualizerGridEmbeddableOutput
>('data_visualizer_grid');
if (factory) {
// Initialize embeddable with information available at mount
const initializedEmbeddable = await factory.create({
id: 'discover_data_visualizer_grid',
dataView,
savedSearch,
query,
showPreviewByDefault,
onAddFilter,
});
if (!unmounted) {
setEmbeddable(initializedEmbeddable);
}
}
const updateState = useCallback(
(changes) => {
if (changes.showDistributions !== undefined && stateContainer) {
stateContainer.appState.update({ hideAggregatedPreview: !changes.showDistributions });
}
};
loadEmbeddable();
return () => {
unmounted = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [services.embeddable, showPreviewByDefault]);

// We can only render after embeddable has already initialized
useEffect(() => {
if (embeddableRoot.current && embeddable) {
embeddable.render(embeddableRoot.current);

trackUiMetric?.(METRIC_TYPE.LOADED, FIELD_STATISTICS_LOADED);
}

return () => {
// Clean up embeddable upon unmounting
embeddable?.destroy();
};
}, [embeddable, embeddableRoot, trackUiMetric]);

const statsTableCss = css`
overflow-y: auto;
},
[stateContainer]
);

.kbnDocTableWrapper {
overflow-x: hidden;
}
`;
if (!dataVisualizerService) return null;

return (
<EuiFlexItem css={statsTableCss}>
<div
data-test-subj="dscFieldStatsEmbeddedContent"
ref={embeddableRoot}
// Match the scroll bar of the Discover doc table
className="kbnDocTableWrapper"
<EuiFlexItem css={statsTableCss} data-test-subj="dscFieldStatsEmbeddedContent">
<dataVisualizerService.FieldStatisticsTable
shouldGetSubfields={true}
dataView={dataView}
savedSearch={savedSearch}
filters={filters}
query={query}
visibleFieldNames={columns}
sessionId={searchSessionId}
totalDocuments={totalDocuments}
samplingOption={samplingOption}
lastReloadRequestTime={lastReloadRequestTime}
onAddFilter={onAddFilter}
showPreviewByDefault={showPreviewByDefault}
onTableUpdate={updateState}
/>
</EuiFlexItem>
);
Expand Down
Loading

0 comments on commit ea4d2c3

Please sign in to comment.