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

Move ensureDefaultIndexPattern into data plugin #63100

Merged
merged 14 commits into from
Apr 24, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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 @@ -20,5 +20,5 @@ export interface DataPublicPluginStart
| [indexPatterns](./kibana-plugin-plugins-data-public.datapublicpluginstart.indexpatterns.md) | <code>IndexPatternsContract</code> | |
| [query](./kibana-plugin-plugins-data-public.datapublicpluginstart.query.md) | <code>QueryStart</code> | |
| [search](./kibana-plugin-plugins-data-public.datapublicpluginstart.search.md) | <code>ISearchStart</code> | |
| [ui](./kibana-plugin-plugins-data-public.datapublicpluginstart.ui.md) | <code>{</code><br/><code> IndexPatternSelect: React.ComponentType&lt;IndexPatternSelectProps&gt;;</code><br/><code> SearchBar: React.ComponentType&lt;StatefulSearchBarProps&gt;;</code><br/><code> }</code> | |
| [ui](./kibana-plugin-plugins-data-public.datapublicpluginstart.ui.md) | <code>{</code><br/><code> IndexPatternSelect: React.ComponentType&lt;IndexPatternSelectProps&gt;;</code><br/><code> SearchBar: React.ComponentType&lt;StatefulSearchBarProps&gt;;</code><br/><code> ensureDefaultIndexPattern: EnsureDefaultIndexPattern;</code><br/><code> }</code> | |

Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@
ui: {
IndexPatternSelect: React.ComponentType<IndexPatternSelectProps>;
SearchBar: React.ComponentType<StatefulSearchBarProps>;
ensureDefaultIndexPattern: EnsureDefaultIndexPattern;
};
```
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,7 @@ export const [getUrlTracker, setUrlTracker] = createGetterSetter<{
}>('urlTracker');

export const { getRequestInspectorStats, getResponseInspectorStats, tabifyAggResponse } = search;
export {
unhashUrl,
redirectWhenMissing,
ensureDefaultIndexPattern,
} from '../../../../../plugins/kibana_utils/public';
export { unhashUrl, redirectWhenMissing } from '../../../../../plugins/kibana_utils/public';
export {
formatMsg,
formatStack,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ import {
subscribeWithScope,
tabifyAggResponse,
getAngularModule,
ensureDefaultIndexPattern,
redirectWhenMissing,
} from '../../kibana_services';

Expand Down Expand Up @@ -118,7 +117,7 @@ app.config($routeProvider => {
resolve: {
savedObjects: function($route, Promise) {
const savedSearchId = $route.current.params.id;
return ensureDefaultIndexPattern(core, data, history).then(() => {
return data.ui.ensureDefaultIndexPattern(history).then(() => {
const { appStateContainer } = getState({ history });
const { index } = appStateContainer.getState();
return Promise.props({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import { createHashHistory } from 'history';
import {
createKbnUrlStateStorage,
redirectWhenMissing,
ensureDefaultIndexPattern,
} from '../../../../../../plugins/kibana_utils/public';

import editorTemplate from './editor/editor.html';
Expand Down Expand Up @@ -126,7 +125,7 @@ export function initVisualizeApp(app, deps) {
controllerAs: 'listingController',
resolve: {
createNewVis: () => false,
hasDefaultIndex: history => ensureDefaultIndexPattern(deps.core, deps.data, history),
hasDefaultIndex: history => deps.data.ui.ensureDefaultIndexPattern(history),
},
})
.when(VisualizeConstants.WIZARD_STEP_1_PAGE_PATH, {
Expand All @@ -137,7 +136,7 @@ export function initVisualizeApp(app, deps) {
controllerAs: 'listingController',
resolve: {
createNewVis: () => true,
hasDefaultIndex: history => ensureDefaultIndexPattern(deps.core, deps.data, history),
hasDefaultIndex: history => deps.data.ui.ensureDefaultIndexPattern(history),
},
})
.when(VisualizeConstants.CREATE_PATH, {
Expand All @@ -146,7 +145,7 @@ export function initVisualizeApp(app, deps) {
k7Breadcrumbs: getCreateBreadcrumbs,
resolve: {
resolved: function($route, history) {
const { core, data, savedVisualizations, visualizations, toastNotifications } = deps;
const { data, savedVisualizations, visualizations, toastNotifications } = deps;
const visTypes = visualizations.all();
const visType = find(visTypes, { name: $route.current.params.type });
const shouldHaveIndex = visType.requiresSearch && visType.options.showIndexSelection;
Expand All @@ -163,7 +162,8 @@ export function initVisualizeApp(app, deps) {
);
}

return ensureDefaultIndexPattern(core, data, history)
return data.ui
.ensureDefaultIndexPattern(history)
.then(() => savedVisualizations.get($route.current.params))
.then(getResolvedResults(deps))
.catch(
Expand All @@ -182,9 +182,10 @@ export function initVisualizeApp(app, deps) {
k7Breadcrumbs: getEditBreadcrumbs,
resolve: {
resolved: function($route, history) {
const { chrome, core, data, savedVisualizations, toastNotifications } = deps;
const { chrome, data, savedVisualizations, toastNotifications } = deps;

return ensureDefaultIndexPattern(core, data, history)
return data.ui
.ensureDefaultIndexPattern(history)
.then(() => savedVisualizations.get($route.current.params.id))
.then(savedVis => {
chrome.recentlyAccessed.add(savedVis.getFullPath(), savedVis.title, savedVis.id);
Expand Down
9 changes: 5 additions & 4 deletions src/plugins/dashboard/public/application/legacy_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import { initDashboardAppDirective } from './dashboard_app';
import { createDashboardEditUrl, DashboardConstants } from '../dashboard_constants';
import {
createKbnUrlStateStorage,
ensureDefaultIndexPattern,
redirectWhenMissing,
InvalidJSONProperty,
SavedObjectNotFound,
Expand Down Expand Up @@ -138,7 +137,7 @@ export function initDashboardApp(app, deps) {
},
resolve: {
dash: function($route, history) {
return ensureDefaultIndexPattern(deps.core, deps.data, history).then(() => {
return deps.data.ui.ensureDefaultIndexPattern(history).then(() => {
const savedObjectsClient = deps.savedObjectsClient;
const title = $route.current.params.title;
if (title) {
Expand Down Expand Up @@ -173,7 +172,8 @@ export function initDashboardApp(app, deps) {
requireUICapability: 'dashboard.createNew',
resolve: {
dash: history =>
ensureDefaultIndexPattern(deps.core, deps.data, history)
deps.data.ui
.ensureDefaultIndexPattern(history)
.then(() => deps.savedDashboards.get())
.catch(
redirectWhenMissing({
Expand All @@ -194,7 +194,8 @@ export function initDashboardApp(app, deps) {
dash: function($route, history) {
const id = $route.current.params.id;

return ensureDefaultIndexPattern(deps.core, deps.data, history)
return deps.data.ui
.ensureDefaultIndexPattern(history)
.then(() => deps.savedDashboards.get(id))
.then(savedDashboard => {
deps.chrome.recentlyAccessed.add(
Expand Down
1 change: 1 addition & 0 deletions src/plugins/data/public/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ const createStartContract = (): Start => {
ui: {
IndexPatternSelect: jest.fn(),
SearchBar: jest.fn(),
ensureDefaultIndexPattern: jest.fn(),
},
indexPatterns: ({
make: () => ({
Expand Down
2 changes: 2 additions & 0 deletions src/plugins/data/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ import {
ACTION_VALUE_CLICK,
ValueClickActionContext,
} from './actions/value_click_action';
import { createEnsureDefaultIndexPattern } from './ui/ensure_default_index_pattern';

declare module '../../ui_actions/public' {
export interface ActionContextMapping {
Expand Down Expand Up @@ -182,6 +183,7 @@ export class DataPublicPlugin implements Plugin<DataPublicPluginSetup, DataPubli
ui: {
IndexPatternSelect: createIndexPatternSelect(core.savedObjects.client),
SearchBar,
ensureDefaultIndexPattern: createEnsureDefaultIndexPattern(core, indexPatterns),
Copy link
Contributor

Choose a reason for hiding this comment

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

I think this should not be exported from here.
It's not really a UI component, and the naming makes it extra unclear.
It looks more like it should be a useDefaultIndexPattern hook, that is exported from kibana_react.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This would be the best way to implement this (except the thing about showing the warning banner, it would be disappeared right after a plugin is destroyed),
but unfortunately, right now it's only used across angular driven plugins and I guess there is no way to integrate this pattern well there

Copy link
Contributor

Choose a reason for hiding this comment

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

@lizozom What do you think about exporting this from IndexPatternsService?

Copy link
Member

Choose a reason for hiding this comment

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

It looks more like it should be a useDefaultIndexPattern hook, that is exported from kibana_react

I agree the ergonomics of this would be better. The only problem is that the way this helper is currently written (with bannerId and timeoutId being stateful), means we really have no choice but to put it somewhere in the runtime contract of the data plugin, as kibana_utils and kibana_react are only imported statically.

I don't have strong feelings on whether it goes in ui or IndexPatternsService, but since it contains state that needs to be shared across apps, it seems those are our only options outside of refactoring the function altogether and storing that state elsewhere (e.g. sessionStorage).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

So what would be the final decision?
Should it stay in ui or moved into IndexPatternsService, or even postponed in respect of #57401 ?

Copy link
Member

Choose a reason for hiding this comment

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

If @lizozom doesn't like the idea of putting it in ui, then IMHO it's fine to put it on IndexPatternsService. She should be available tomorrow and can hopefully chime in if she has any other ideas.

or even postponed in respect of #57401 ?

I don't think we should wait on that issue to fix this bug. That discussion is still in early stages & I don't know when the actual implementation will be prioritized.

Copy link
Contributor

Choose a reason for hiding this comment

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

@sulemanof

I think moving it to the index pattern service is better.
It's not an actual UI component.

Thanks!

},
};
}
Expand Down
6 changes: 4 additions & 2 deletions src/plugins/data/public/public.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ export interface DataPublicPluginStart {
ui: {
IndexPatternSelect: React.ComponentType<IndexPatternSelectProps>;
SearchBar: React.ComponentType<StatefulSearchBarProps>;
ensureDefaultIndexPattern: EnsureDefaultIndexPattern;
};
}

Expand Down Expand Up @@ -1898,8 +1899,9 @@ export type TSearchStrategyProvider<T extends TStrategyTypes> = (context: ISearc
// src/plugins/data/public/index.ts:412:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts
// src/plugins/data/public/query/state_sync/connect_to_query_state.ts:33:33 - (ae-forgotten-export) The symbol "FilterStateStore" needs to be exported by the entry point index.d.ts
// src/plugins/data/public/query/state_sync/connect_to_query_state.ts:37:1 - (ae-forgotten-export) The symbol "QueryStateChange" needs to be exported by the entry point index.d.ts
// src/plugins/data/public/types.ts:52:5 - (ae-forgotten-export) The symbol "createFiltersFromEvent" needs to be exported by the entry point index.d.ts
// src/plugins/data/public/types.ts:60:5 - (ae-forgotten-export) The symbol "IndexPatternSelectProps" needs to be exported by the entry point index.d.ts
// src/plugins/data/public/types.ts:53:5 - (ae-forgotten-export) The symbol "createFiltersFromEvent" needs to be exported by the entry point index.d.ts
// src/plugins/data/public/types.ts:61:5 - (ae-forgotten-export) The symbol "IndexPatternSelectProps" needs to be exported by the entry point index.d.ts
// src/plugins/data/public/types.ts:63:5 - (ae-forgotten-export) The symbol "EnsureDefaultIndexPattern" needs to be exported by the entry point index.d.ts

// (No @packageDocumentation comment for this package)

Expand Down
2 changes: 2 additions & 0 deletions src/plugins/data/public/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { QuerySetup, QueryStart } from './query';
import { IndexPatternSelectProps } from './ui/index_pattern_select';
import { IndexPatternsContract } from './index_patterns';
import { StatefulSearchBarProps } from './ui/search_bar/create_search_bar';
import { EnsureDefaultIndexPattern } from './ui/ensure_default_index_pattern';

export interface DataSetupDependencies {
expressions: ExpressionsSetup;
Expand Down Expand Up @@ -59,6 +60,7 @@ export interface DataPublicPluginStart {
ui: {
IndexPatternSelect: React.ComponentType<IndexPatternSelectProps>;
SearchBar: React.ComponentType<StatefulSearchBarProps>;
ensureDefaultIndexPattern: EnsureDefaultIndexPattern;
};
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { contains } from 'lodash';
import React from 'react';
import { History } from 'history';
import { i18n } from '@kbn/i18n';
import { EuiCallOut } from '@elastic/eui';
import { CoreStart } from 'kibana/public';
import { toMountPoint } from '../../../../kibana_react/public';
import { IndexPatternsContract } from '../../index_patterns';

export type EnsureDefaultIndexPattern = (history: History) => Promise<unknown> | undefined;

export const createEnsureDefaultIndexPattern = (
core: CoreStart,
indexPatterns: IndexPatternsContract
) => {
let bannerId: string;
let timeoutId: NodeJS.Timeout | undefined;

/**
* Checks whether a default index pattern is set and exists and defines
* one otherwise.
*
* If there are no index patterns, redirect to management page and show
* banner. In this case the promise returned from this function will never
* resolve to wait for the URL change to happen.
*/
return async function ensureDefaultIndexPattern(history: History) {
const patterns = await indexPatterns.getIds();
let defaultId = core.uiSettings.get('defaultIndex');
let defined = !!defaultId;
const exists = contains(patterns, defaultId);

if (defined && !exists) {
core.uiSettings.remove('defaultIndex');
defaultId = defined = false;
}

if (defined) {
return;
}

// If there is any index pattern created, set the first as default
if (patterns.length >= 1) {
defaultId = patterns[0];
core.uiSettings.set('defaultIndex', defaultId);
} else {
const canManageIndexPatterns = core.application.capabilities.management.kibana.index_patterns;
const redirectTarget = canManageIndexPatterns ? '/management/kibana/index_pattern' : '/home';

if (timeoutId) {
clearTimeout(timeoutId);
}

// Avoid being hostile to new users who don't have an index pattern setup yet
// give them a friendly info message instead of a terse error message
bannerId = core.overlays.banners.replace(
bannerId,
toMountPoint(
<EuiCallOut
color="warning"
iconType="iInCircle"
title={i18n.translate('data.ensureDefaultIndexPattern.bannerLabel', {
defaultMessage:
"In order to visualize and explore data in Kibana, you'll need to create an index pattern to retrieve data from Elasticsearch.",
})}
/>
)
);

// hide the message after the user has had a chance to acknowledge it -- so it doesn't permanently stick around
timeoutId = setTimeout(() => {
core.overlays.banners.remove(bannerId);
timeoutId = undefined;
}, 15000);

history.push(redirectTarget);

// return never-resolving promise to stop resolving and wait for the url change
return new Promise(() => {});
}
};
};
23 changes: 23 additions & 0 deletions src/plugins/data/public/ui/ensure_default_index_pattern/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

export {
createEnsureDefaultIndexPattern,
EnsureDefaultIndexPattern,
} from './ensure_default_index_pattern';
Loading