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

[Graph] Switch to SavedObjectClient.resolve #109617

Merged
merged 9 commits into from
Sep 10, 2021
Merged
Show file tree
Hide file tree
Changes from 7 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
27 changes: 22 additions & 5 deletions x-pack/plugins/graph/kibana.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,29 @@
"kibanaVersion": "kibana",
"server": true,
"ui": true,
"requiredPlugins": ["licensing", "data", "navigation", "savedObjects", "kibanaLegacy"],
"optionalPlugins": ["home", "features"],
"configPath": ["xpack", "graph"],
"requiredBundles": ["kibanaUtils", "kibanaReact", "home"],
"requiredPlugins": [
"licensing",
"data",
"navigation",
"savedObjects",
"kibanaLegacy"
],
"optionalPlugins": [
"home",
"features",
"spaces"
],
"configPath": [
"xpack",
"graph"
],
"requiredBundles": [
"kibanaUtils",
"kibanaReact",
"home"
],
"owner": {
"name": "Data Discovery",
"githubTeam": "kibana-data-discovery"
}
}
}
2 changes: 2 additions & 0 deletions x-pack/plugins/graph/public/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import './index.scss';
import { SavedObjectsStart } from '../../../../src/plugins/saved_objects/public';
import { GraphSavePolicy } from './types';
import { graphRouter } from './router';
import { SpacesApi } from '../../spaces/public';

/**
* These are dependencies of the Graph app besides the base dependencies
Expand Down Expand Up @@ -63,6 +64,7 @@ export interface GraphDependencies {
setHeaderActionMenu: AppMountParameters['setHeaderActionMenu'];
uiSettings: IUiSettingsClient;
history: ScopedHistory<unknown>;
spaces?: SpacesApi;
}

export type GraphServices = Omit<GraphDependencies, 'kibanaLegacy' | 'element' | 'history'>;
Expand Down
14 changes: 12 additions & 2 deletions x-pack/plugins/graph/public/apps/workspace_route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const WorkspaceRoute = ({
getBasePath,
addBasePath,
setHeaderActionMenu,
spaces,
indexPatterns: getIndexPatternProvider,
},
}: WorkspaceRouteProps) => {
Expand Down Expand Up @@ -114,13 +115,20 @@ export const WorkspaceRoute = ({
})
);

const { savedWorkspace, indexPatterns } = useWorkspaceLoader({
const loaded = useWorkspaceLoader({
workspaceRef,
store,
savedObjectsClient,
toastNotifications,
spaces,
coreStart,
});

if (!loaded) {
return null;
}

const { savedWorkspace, indexPatterns, sharingSavedObjectProps } = loaded;

if (!savedWorkspace || !indexPatterns) {
mbondyra marked this conversation as resolved.
Show resolved Hide resolved
return null;
}
Expand All @@ -130,6 +138,8 @@ export const WorkspaceRoute = ({
<KibanaContextProvider services={services}>
<Provider store={store}>
<WorkspaceLayout
spaces={spaces}
sharingSavedObjectProps={sharingSavedObjectProps}
renderCounter={renderCounter}
workspace={workspaceRef.current}
loading={loading}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* 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 React from 'react';
import { shallow } from 'enzyme';
import { WorkspaceLayoutComponent } from '.';
import { coreMock } from 'src/core/public/mocks';
import { spacesPluginMock } from '../../../../spaces/public/mocks';
import { NavigationPublicPluginStart as NavigationStart } from '../../../../../../src/plugins/navigation/public';
import { GraphSavePolicy, GraphWorkspaceSavedObject, IndexPatternProvider } from '../../types';
import { OverlayStart, Capabilities } from 'kibana/public';
import { SharingSavedObjectProps } from '../../helpers/use_workspace_loader';

describe('workspace_layout', () => {
const defaultProps = {
renderCounter: 1,
loading: false,
savedWorkspace: { id: 'test' } as GraphWorkspaceSavedObject,
hasFields: true,
overlays: {} as OverlayStart,
workspaceInitialized: true,
indexPatterns: [],
indexPatternProvider: {} as IndexPatternProvider,
capabilities: {} as Capabilities,
coreStart: coreMock.createStart(),
graphSavePolicy: 'configAndDataWithConsent' as GraphSavePolicy,
navigation: {} as NavigationStart,
canEditDrillDownUrls: true,
urlQuery: 'search',
setHeaderActionMenu: jest.fn(),
sharingSavedObjectProps: {
outcome: 'exactMatch',
aliasTargetId: '',
} as SharingSavedObjectProps,
spaces: spacesPluginMock.createStartContract(),
};
it('should display conflict notification if outcome is conflict', () => {
shallow(
<WorkspaceLayoutComponent
{...defaultProps}
sharingSavedObjectProps={{ outcome: 'conflict', aliasTargetId: 'conflictId' }}
/>
);
expect(defaultProps.spaces.ui.components.getLegacyUrlConflict).toHaveBeenCalledWith({
currentObjectId: 'test',
objectNoun: 'Graph',
otherObjectId: 'conflictId',
otherObjectPath: '#/workspace/conflictId',
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ import { GraphServices } from '../../application';
import { ControlPanel } from '../control_panel';
import { GraphVisualization } from '../graph_visualization';
import { colorChoices } from '../../helpers/style_choices';
import { SharingSavedObjectProps } from '../../helpers/use_workspace_loader';
import { getEditUrl } from '../../services/url';

/**
* Each component, which depends on `worksapce`
Expand All @@ -51,6 +53,7 @@ type WorkspaceLayoutProps = Pick<
| 'coreStart'
| 'canEditDrillDownUrls'
| 'overlays'
| 'spaces'
> & {
renderCounter: number;
workspace?: Workspace;
Expand All @@ -59,14 +62,15 @@ type WorkspaceLayoutProps = Pick<
savedWorkspace: GraphWorkspaceSavedObject;
indexPatternProvider: IndexPatternProvider;
urlQuery: string | null;
sharingSavedObjectProps?: SharingSavedObjectProps;
};

interface WorkspaceLayoutStateProps {
workspaceInitialized: boolean;
hasFields: boolean;
}

const WorkspaceLayoutComponent = ({
export const WorkspaceLayoutComponent = ({
renderCounter,
workspace,
loading,
Expand All @@ -83,6 +87,8 @@ const WorkspaceLayoutComponent = ({
canEditDrillDownUrls,
urlQuery,
setHeaderActionMenu,
sharingSavedObjectProps,
spaces,
}: WorkspaceLayoutProps & WorkspaceLayoutStateProps) => {
const [currentIndexPattern, setCurrentIndexPattern] = useState<IndexPattern>();
const [showInspect, setShowInspect] = useState(false);
Expand Down Expand Up @@ -154,6 +160,26 @@ const WorkspaceLayoutComponent = ({
[]
);

const getLegacyUrlConflictCallout = useCallback(() => {
// This function returns a callout component *if* we have encountered a "legacy URL conflict" scenario
const currentObjectId = savedWorkspace.id;
if (spaces && sharingSavedObjectProps?.outcome === 'conflict' && currentObjectId) {
// We have resolved to one object, but another object has a legacy URL alias associated with this ID/page. We should display a
// callout with a warning for the user, and provide a way for them to navigate to the other object.
const otherObjectId = sharingSavedObjectProps?.aliasTargetId!; // This is always defined if outcome === 'conflict'
const otherObjectPath = getEditUrl(coreStart.http.basePath.prepend, { id: otherObjectId });
return spaces.ui.components.getLegacyUrlConflict({
objectNoun: i18n.translate('xpack.graph.legacyUrlConflict.objectNoun', {
defaultMessage: 'Graph',
}),
currentObjectId,
otherObjectId,
otherObjectPath,
mbondyra marked this conversation as resolved.
Show resolved Hide resolved
});
}
return null;
}, [savedWorkspace.id, sharingSavedObjectProps, spaces, coreStart.http]);

return (
<Fragment>
<WorkspaceTopNavMenu
Expand All @@ -176,7 +202,6 @@ const WorkspaceLayoutComponent = ({
lastResponse={workspace?.lastResponse}
indexPattern={currentIndexPattern}
/>

{isInitialized && <GraphTitle />}
<div className="gphGraph__bar">
<SearchBar
Expand All @@ -190,6 +215,7 @@ const WorkspaceLayoutComponent = ({
<EuiSpacer size="s" />
<FieldManagerMemoized pickerOpen={pickerOpen} setPickerOpen={setPickerOpen} />
</div>
{getLegacyUrlConflictCallout()}
{!isInitialized && (
<div>
<GuidancePanelMemoized
Expand Down
46 changes: 32 additions & 14 deletions x-pack/plugins/graph/public/helpers/saved_workspace_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,28 +82,38 @@ export function findSavedWorkspace(
});
}

export function getEmptyWorkspace() {
return {
savedObject: {
displayName: 'graph workspace',
getEsType: () => savedWorkspaceType,
...defaultsProps,
} as GraphWorkspaceSavedObject,
};
}

export async function getSavedWorkspace(
savedObjectsClient: SavedObjectsClientContract,
id?: string
id: string
) {
const savedObject = {
id,
displayName: 'graph workspace',
getEsType: () => savedWorkspaceType,
} as { [key: string]: any };

if (!id) {
assign(savedObject, defaultsProps);
return Promise.resolve(savedObject);
}
const resolveResult = await savedObjectsClient.resolve<Record<string, unknown>>(
savedWorkspaceType,
id
);

const resp = await savedObjectsClient.get<Record<string, unknown>>(savedWorkspaceType, id);
savedObject._source = cloneDeep(resp.attributes);
const resp = resolveResult.saved_object;

if (!resp._version) {
throw new SavedObjectNotFound(savedWorkspaceType, id || '');
}

const savedObject = {
id,
displayName: 'graph workspace',
getEsType: () => savedWorkspaceType,
_source: cloneDeep(resp.attributes),
} as GraphWorkspaceSavedObject;

// assign the defaults to the response
defaults(savedObject._source, defaultsProps);

Expand All @@ -120,7 +130,15 @@ export async function getSavedWorkspace(
injectReferences(savedObject, resp.references);
}

return savedObject as GraphWorkspaceSavedObject;
const sharingSavedObjectProps = {
outcome: resolveResult.outcome,
aliasTargetId: resolveResult.alias_target_id,
};

return {
savedObject,
sharingSavedObjectProps,
};
}

export function deleteSavedWorkspace(
Expand Down
95 changes: 95 additions & 0 deletions x-pack/plugins/graph/public/helpers/use_workspace_loader.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* 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 React from 'react';
import { mount } from 'enzyme';
import { useWorkspaceLoader, UseWorkspaceLoaderProps } from './use_workspace_loader';
import { coreMock } from 'src/core/public/mocks';
import { spacesPluginMock } from '../../../spaces/public/mocks';
import { createMockGraphStore } from '../state_management/mocks';
import { Workspace } from '../types';
import { SavedObjectsClientCommon } from 'src/plugins/data/common';
import { act } from 'react-dom/test-utils';

jest.mock('react-router-dom', () => {
const useLocation = () => ({
search: '2',
});

const replaceFn = jest.fn();

const useHistory = () => ({
replace: replaceFn,
});
return {
useHistory,
useLocation,
useParams: () => ({
id: '1',
}),
};
});

const mockSavedObjectsClient = ({
resolve: jest.fn().mockResolvedValue({
saved_object: { id: 10, _version: '7.15.0', attributes: { wsState: '{}' } },
outcome: 'exactMatch',
}),
find: jest.fn().mockResolvedValue({ title: 'test' }),
} as unknown) as SavedObjectsClientCommon;

async function setup(props: UseWorkspaceLoaderProps) {
const returnVal = {};
function TestComponent() {
Object.assign(returnVal, useWorkspaceLoader(props));
return null;
}
await act(async () => {
const promise = Promise.resolve();
mount(<TestComponent />);
await act(() => promise);
});
return returnVal;
}

describe('use_workspace_loader', () => {
const defaultProps = {
workspaceRef: { current: {} as Workspace },
store: createMockGraphStore({}).store,
savedObjectsClient: mockSavedObjectsClient,
coreStart: coreMock.createStart(),
spaces: spacesPluginMock.createStartContract(),
};

it('should not redirect if outcome is exactMatch', async () => {
await act(async () => {
await setup((defaultProps as unknown) as UseWorkspaceLoaderProps);
});
expect(defaultProps.spaces.ui.redirectLegacyUrl).not.toHaveBeenCalled();
expect(defaultProps.store.dispatch).toHaveBeenCalled();
});
it('should redirect if outcome is aliasMatch', async () => {
const props = {
...defaultProps,
spaces: spacesPluginMock.createStartContract(),
savedObjectsClient: {
...mockSavedObjectsClient,
resolve: jest.fn().mockResolvedValue({
saved_object: { id: 10, _version: '7.15.0', attributes: { wsState: '{}' } },
outcome: 'aliasMatch',
alias_target_id: 'aliasTargetId',
}),
},
};
await act(async () => {
await setup((props as unknown) as UseWorkspaceLoaderProps);
});
expect(props.spaces.ui.redirectLegacyUrl).toHaveBeenCalledWith(
'#/workspace/aliasTargetId',
'Graph'
);
});
});
Loading