Skip to content

Commit

Permalink
[Lens] removes DatasourcePublicAPI (#170725)
Browse files Browse the repository at this point in the history
## Summary

We have 2 very similar structures in Lens - FramePublicAPI and
DatasourcePublicAPI. Creating `DatasourcePublicAPI` was an attempt to
remove framePublicAPI by firstly limiting it and then just using redux
store directly. Unfortunately, due to Lens architecture it never
progressed so we're stuck with those two structures for no reason
whatsover. This PR merges them back together.

Apart from that it also moves some code from app.tsx to the hook that is
responsible for creating `getUserMessages` helper. This way we could use
it in other places (inline editor, for example)


### 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
- [ ] [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
- [ ] 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)
  • Loading branch information
mbondyra authored Nov 9, 2023
1 parent 0b40e3e commit 5fa46ca
Show file tree
Hide file tree
Showing 26 changed files with 289 additions and 273 deletions.
116 changes: 19 additions & 97 deletions x-pack/plugins/lens/public/app_plugin/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import type { LensAppLocatorParams } from '../../common/locator/locator';
import { LensAppProps, LensAppServices } from './types';
import { LensTopNavMenu } from './lens_top_nav';
import { LensByReferenceInput } from '../embeddable';
import { AddUserMessages, EditorFrameInstance, UserMessage, UserMessagesGetter } from '../types';
import { AddUserMessages, EditorFrameInstance, UserMessagesGetter } from '../types';
import { Document } from '../persistence/saved_object_store';

import {
Expand All @@ -28,9 +28,8 @@ import {
LensAppState,
selectSavedObjectFormat,
updateIndexPatterns,
updateDatasourceState,
selectActiveDatasourceId,
selectFrameDatasourceAPI,
selectFramePublicAPI,
} from '../state_management';
import { SaveModalContainer, runSaveLensVisualization } from './save_modal_container';
import { LensInspector } from '../lens_inspector_service';
Expand All @@ -41,10 +40,7 @@ import {
createIndexPatternService,
} from '../data_views_service/service';
import { replaceIndexpattern } from '../state_management/lens_slice';
import {
filterAndSortUserMessages,
getApplicationUserMessages,
} from './get_application_user_messages';
import { useApplicationUserMessages } from './get_application_user_messages';

export type SaveProps = Omit<OnSaveProps, 'onTitleDuplicate' | 'newDescription'> & {
returnToOrigin: boolean;
Expand Down Expand Up @@ -509,99 +505,25 @@ export function App({

const activeDatasourceId = useLensSelector(selectActiveDatasourceId);

const frameDatasourceAPI = useLensSelector((state) =>
selectFrameDatasourceAPI(state, datasourceMap)
);

const [userMessages, setUserMessages] = useState<UserMessage[]>([]);
const framePublicAPI = useLensSelector((state) => selectFramePublicAPI(state, datasourceMap));

useEffect(() => {
setUserMessages([
...(activeDatasourceId
? datasourceMap[activeDatasourceId].getUserMessages(
datasourceStates[activeDatasourceId].state,
{
frame: frameDatasourceAPI,
setState: (newStateOrUpdater) => {
dispatch(
updateDatasourceState({
newDatasourceState:
typeof newStateOrUpdater === 'function'
? newStateOrUpdater(datasourceStates[activeDatasourceId].state)
: newStateOrUpdater,
datasourceId: activeDatasourceId,
})
);
},
}
)
: []),
...(visualization.activeId && visualization.state
? visualizationMap[visualization.activeId]?.getUserMessages?.(visualization.state, {
frame: frameDatasourceAPI,
}) ?? []
: []),
...getApplicationUserMessages({
visualizationType: persistedDoc?.visualizationType,
visualizationMap,
visualization,
activeDatasource: activeDatasourceId ? datasourceMap[activeDatasourceId] : null,
activeDatasourceState: activeDatasourceId ? datasourceStates[activeDatasourceId] : null,
core: coreStart,
dataViews: frameDatasourceAPI.dataViews,
}),
]);
}, [
activeDatasourceId,
const { getUserMessages, addUserMessages } = useApplicationUserMessages({
coreStart,
datasourceMap,
datasourceStates,
framePublicAPI,
activeDatasourceId,
datasourceState:
activeDatasourceId && datasourceStates[activeDatasourceId]
? datasourceStates[activeDatasourceId]
: null,
datasource:
activeDatasourceId && datasourceMap[activeDatasourceId]
? datasourceMap[activeDatasourceId]
: null,
dispatch,
frameDatasourceAPI,
persistedDoc?.visualizationType,
visualization,
visualizationMap,
]);

// these are messages managed from other parts of Lens
const [additionalUserMessages, setAdditionalUserMessages] = useState<Record<string, UserMessage>>(
{}
);

const getUserMessages: UserMessagesGetter = (locationId, filterArgs) =>
filterAndSortUserMessages(
[...userMessages, ...Object.values(additionalUserMessages)],
locationId,
filterArgs ?? {}
);

const addUserMessages: AddUserMessages = (messages) => {
const newMessageMap = {
...additionalUserMessages,
};

const addedMessageIds: string[] = [];
messages.forEach((message) => {
if (!newMessageMap[message.uniqueId]) {
addedMessageIds.push(message.uniqueId);
newMessageMap[message.uniqueId] = message;
}
});

if (addedMessageIds.length) {
setAdditionalUserMessages(newMessageMap);
}

return () => {
const withMessagesRemoved = {
...additionalUserMessages,
};

addedMessageIds.forEach((id) => delete withMessagesRemoved[id]);

setAdditionalUserMessages(withMessagesRemoved);
};
};
visualization: visualization.activeId ? visualizationMap[visualization.activeId] : undefined,
visualizationType: visualization.activeId,
visualizationState: visualization,
});

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ describe('application-level user messages', () => {
getApplicationUserMessages({
visualizationType: undefined,

visualizationMap: {},
visualization: { activeId: '', state: {} },
visualization: undefined,
visualizationState: { activeId: '', state: {} },
activeDatasource: {} as Datasource,
activeDatasourceState: null,
dataViews: {} as DataViewsState,
Expand All @@ -53,8 +53,8 @@ describe('application-level user messages', () => {
expect(
getApplicationUserMessages({
visualizationType: '123',
visualizationMap: {},
visualization: { activeId: 'id_for_type_that_doesnt_exist', state: {} },
visualization: undefined,
visualizationState: { activeId: 'id_for_type_that_doesnt_exist', state: {} },

activeDatasource: {} as Datasource,
activeDatasourceState: null,
Expand Down Expand Up @@ -84,8 +84,8 @@ describe('application-level user messages', () => {
activeDatasource: null,

visualizationType: '123',
visualizationMap: { 'some-id': {} as Visualization },
visualization: { activeId: 'some-id', state: {} },
visualization: {} as Visualization,
visualizationState: { activeId: 'some-id', state: {} },
activeDatasourceState: null,
dataViews: {} as DataViewsState,
core: {} as CoreStart,
Expand Down Expand Up @@ -138,8 +138,8 @@ describe('application-level user messages', () => {

const irrelevantProps = {
dataViews: {} as DataViewsState,
visualizationMap: { foo: {} as Visualization },
visualization: { activeId: 'foo', state: {} },
visualization: {} as Visualization,
visualizationState: { activeId: 'foo', state: {} },
};

it('generates error if missing an index pattern', () => {
Expand Down
138 changes: 128 additions & 10 deletions x-pack/plugins/lens/public/app_plugin/get_application_user_messages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,27 @@
* 2.0.
*/

import React from 'react';
import React, { useEffect, useState } from 'react';
import { i18n } from '@kbn/i18n';
import { RedirectAppLinks } from '@kbn/shared-ux-link-redirect-app';
import { FormattedMessage } from '@kbn/i18n-react';
import type { CoreStart } from '@kbn/core/public';
import type { DataViewsState, VisualizationState } from '../state_management';
import { Dispatch } from '@reduxjs/toolkit';
import {
updateDatasourceState,
type DataViewsState,
type VisualizationState,
DatasourceState,
} from '../state_management';
import type {
AddUserMessages,
Datasource,
FramePublicAPI,
UserMessage,
UserMessageFilters,
UserMessagesDisplayLocationId,
VisualizationMap,
UserMessagesGetter,
Visualization,
} from '../types';
import { getMissingIndexPattern } from '../editor_frame_service/editor_frame/state_helpers';

Expand All @@ -26,15 +35,15 @@ import { getMissingIndexPattern } from '../editor_frame_service/editor_frame/sta
export const getApplicationUserMessages = ({
visualizationType,
visualization,
visualizationMap,
visualizationState,
activeDatasource,
activeDatasourceState,
dataViews,
core,
}: {
visualizationType: string | null | undefined;
visualization: VisualizationState | undefined;
visualizationMap: VisualizationMap;
visualization: Visualization | undefined;
visualizationState: VisualizationState | undefined;
activeDatasource: Datasource | null | undefined;
activeDatasourceState: { isLoading: boolean; state: unknown } | null;
dataViews: DataViewsState;
Expand All @@ -46,8 +55,8 @@ export const getApplicationUserMessages = ({
messages.push(getMissingVisTypeError());
}

if (visualization?.activeId && !visualizationMap[visualization.activeId]) {
messages.push(getUnknownVisualizationTypeError(visualization.activeId));
if (visualizationState?.activeId && !visualization) {
messages.push(getUnknownVisualizationTypeError(visualizationState.activeId));
}

if (!activeDatasource) {
Expand Down Expand Up @@ -182,8 +191,8 @@ function getMissingIndexPatternsErrors(

export const filterAndSortUserMessages = (
userMessages: UserMessage[],
locationId: UserMessagesDisplayLocationId | UserMessagesDisplayLocationId[] | undefined,
{ dimensionId, severity }: UserMessageFilters
locationId?: UserMessagesDisplayLocationId | UserMessagesDisplayLocationId[],
{ dimensionId, severity }: UserMessageFilters = {}
) => {
const locationIds = Array.isArray(locationId)
? locationId
Expand Down Expand Up @@ -231,3 +240,112 @@ function bySeverity(a: UserMessage, b: UserMessage) {
}
return 1;
}

export const useApplicationUserMessages = ({
coreStart,
dispatch,
activeDatasourceId,
datasource,
datasourceState,
framePublicAPI,
visualizationType,
visualization,
visualizationState,
}: {
activeDatasourceId: string | null;
coreStart: CoreStart;
datasource: Datasource | null;
datasourceState: DatasourceState | null;
dispatch: Dispatch;
framePublicAPI: FramePublicAPI;
visualizationType: string | null;
visualizationState?: VisualizationState;
visualization?: Visualization;
}) => {
const [userMessages, setUserMessages] = useState<UserMessage[]>([]);
// these are messages managed from other parts of Lens
const [additionalUserMessages, setAdditionalUserMessages] = useState<Record<string, UserMessage>>(
{}
);

useEffect(() => {
setUserMessages([
...(datasourceState && datasourceState.state && datasource && activeDatasourceId
? datasource.getUserMessages(datasourceState.state, {
frame: framePublicAPI,
setState: (newStateOrUpdater) => {
dispatch(
updateDatasourceState({
newDatasourceState:
typeof newStateOrUpdater === 'function'
? newStateOrUpdater(datasourceState.state)
: newStateOrUpdater,
datasourceId: activeDatasourceId,
})
);
},
})
: []),
...(visualizationState?.activeId && visualizationState.state
? visualization?.getUserMessages?.(visualizationState.state, {
frame: framePublicAPI,
}) ?? []
: []),
...getApplicationUserMessages({
visualizationType,
visualization,
visualizationState,
activeDatasource: datasource,
activeDatasourceState: datasourceState,
core: coreStart,
dataViews: framePublicAPI.dataViews,
}),
]);
}, [
activeDatasourceId,
datasource,
datasourceState,
dispatch,
framePublicAPI,
visualization,
visualizationState,
visualizationType,
coreStart,
]);

const getUserMessages: UserMessagesGetter = (locationId, filterArgs) =>
filterAndSortUserMessages(
[...userMessages, ...Object.values(additionalUserMessages)],
locationId,
filterArgs ?? {}
);

const addUserMessages: AddUserMessages = (messages) => {
const newMessageMap = {
...additionalUserMessages,
};

const addedMessageIds: string[] = [];
messages.forEach((message) => {
if (!newMessageMap[message.uniqueId]) {
addedMessageIds.push(message.uniqueId);
newMessageMap[message.uniqueId] = message;
}
});

if (addedMessageIds.length) {
setAdditionalUserMessages(newMessageMap);
}

return () => {
const withMessagesRemoved = {
...additionalUserMessages,
};

addedMessageIds.forEach((id) => delete withMessagesRemoved[id]);

setAdditionalUserMessages(withMessagesRemoved);
};
};
return { getUserMessages, addUserMessages };
};
Loading

0 comments on commit 5fa46ca

Please sign in to comment.