From 44f594ee7b366e6eb304a008d1ed2bc0302bd1f6 Mon Sep 17 00:00:00 2001 From: Daniil Suleiman <31325372+sulemanof@users.noreply.github.com> Date: Mon, 14 Sep 2020 13:36:42 +0300 Subject: [PATCH 1/6] [Visualizations] Simplify visualization telemetry (#77145) * Move visualizations telemetry into visualizations plugin * Remove x-pack oss_telemetry plugin * Add unit tests * Update docs * Revert not related changes Co-authored-by: Elastic Machine --- docs/developer/plugin-list.asciidoc | 4 - src/plugins/visualizations/server/plugin.ts | 11 +- .../usage_collector/get_past_days.test.ts | 35 +++ .../server/usage_collector/get_past_days.ts | 25 +++ .../get_usage_collector.test.ts | 195 ++++++++++++++++ .../usage_collector/get_usage_collector.ts | 107 +++++++++ .../server/usage_collector/index.ts | 31 +++ x-pack/plugins/oss_telemetry/constants.ts | 9 - x-pack/plugins/oss_telemetry/kibana.json | 9 - x-pack/plugins/oss_telemetry/server/index.ts | 12 - .../server/lib/collectors/index.ts | 16 -- .../get_usage_collector.test.ts | 69 ------ .../visualizations/get_usage_collector.ts | 42 ---- .../register_usage_collector.ts | 17 -- .../server/lib/get_next_midnight.test.ts | 16 -- .../server/lib/get_next_midnight.ts | 12 - .../server/lib/get_past_days.test.ts | 22 -- .../oss_telemetry/server/lib/get_past_days.ts | 11 - .../oss_telemetry/server/lib/tasks/index.ts | 73 ------ .../tasks/visualizations/task_runner.test.ts | 211 ------------------ .../lib/tasks/visualizations/task_runner.ts | 114 ---------- x-pack/plugins/oss_telemetry/server/plugin.ts | 53 ----- .../oss_telemetry/server/test_utils/index.ts | 90 -------- 23 files changed, 403 insertions(+), 781 deletions(-) create mode 100644 src/plugins/visualizations/server/usage_collector/get_past_days.test.ts create mode 100644 src/plugins/visualizations/server/usage_collector/get_past_days.ts create mode 100644 src/plugins/visualizations/server/usage_collector/get_usage_collector.test.ts create mode 100644 src/plugins/visualizations/server/usage_collector/get_usage_collector.ts create mode 100644 src/plugins/visualizations/server/usage_collector/index.ts delete mode 100644 x-pack/plugins/oss_telemetry/constants.ts delete mode 100644 x-pack/plugins/oss_telemetry/kibana.json delete mode 100644 x-pack/plugins/oss_telemetry/server/index.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/lib/collectors/index.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/get_usage_collector.test.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/get_usage_collector.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/register_usage_collector.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/lib/get_next_midnight.test.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/lib/get_next_midnight.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/lib/get_past_days.test.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/lib/get_past_days.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/lib/tasks/index.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/lib/tasks/visualizations/task_runner.test.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/lib/tasks/visualizations/task_runner.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/plugin.ts delete mode 100644 x-pack/plugins/oss_telemetry/server/test_utils/index.ts diff --git a/docs/developer/plugin-list.asciidoc b/docs/developer/plugin-list.asciidoc index 88f29fa7e3cbe9..275fdf8fb69ad6 100644 --- a/docs/developer/plugin-list.asciidoc +++ b/docs/developer/plugin-list.asciidoc @@ -416,10 +416,6 @@ using the CURL scripts in the scripts folder. |This plugin provides shared components and services for use across observability solutions, as well as the observability landing page UI. -|{kib-repo}blob/{branch}/x-pack/plugins/oss_telemetry[ossTelemetry] -|WARNING: Missing README. - - |{kib-repo}blob/{branch}/x-pack/plugins/painless_lab[painlessLab] |WARNING: Missing README. diff --git a/src/plugins/visualizations/server/plugin.ts b/src/plugins/visualizations/server/plugin.ts index 993612d22ebfd5..7502968a336541 100644 --- a/src/plugins/visualizations/server/plugin.ts +++ b/src/plugins/visualizations/server/plugin.ts @@ -19,6 +19,8 @@ import { i18n } from '@kbn/i18n'; import { schema } from '@kbn/config-schema'; +import { Observable } from 'rxjs'; +import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; import { PluginInitializerContext, CoreSetup, @@ -32,16 +34,19 @@ import { VISUALIZE_ENABLE_LABS_SETTING } from '../common/constants'; import { visualizationSavedObjectType } from './saved_objects'; import { VisualizationsPluginSetup, VisualizationsPluginStart } from './types'; +import { registerVisualizationsCollector } from './usage_collector'; export class VisualizationsPlugin implements Plugin { private readonly logger: Logger; + private readonly config: Observable<{ kibana: { index: string } }>; constructor(initializerContext: PluginInitializerContext) { this.logger = initializerContext.logger.get(); + this.config = initializerContext.config.legacy.globalConfig$; } - public setup(core: CoreSetup) { + public setup(core: CoreSetup, plugins: { usageCollection?: UsageCollectionSetup }) { this.logger.debug('visualizations: Setup'); core.savedObjects.registerType(visualizationSavedObjectType); @@ -61,6 +66,10 @@ export class VisualizationsPlugin }, }); + if (plugins.usageCollection) { + registerVisualizationsCollector(plugins.usageCollection, this.config); + } + return {}; } diff --git a/src/plugins/visualizations/server/usage_collector/get_past_days.test.ts b/src/plugins/visualizations/server/usage_collector/get_past_days.test.ts new file mode 100644 index 00000000000000..7ef3009de9e5cf --- /dev/null +++ b/src/plugins/visualizations/server/usage_collector/get_past_days.test.ts @@ -0,0 +1,35 @@ +/* + * 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 moment from 'moment'; +import { getPastDays } from './get_past_days'; + +describe('getPastDays', () => { + test('Returns 2 days that have passed from the current date', () => { + const pastDate = moment().subtract(2, 'days').startOf('day').toString(); + + expect(getPastDays(pastDate)).toEqual(2); + }); + + test('Returns 30 days that have passed from the current date', () => { + const pastDate = moment().subtract(30, 'days').startOf('day').toString(); + + expect(getPastDays(pastDate)).toEqual(30); + }); +}); diff --git a/src/plugins/visualizations/server/usage_collector/get_past_days.ts b/src/plugins/visualizations/server/usage_collector/get_past_days.ts new file mode 100644 index 00000000000000..5fa68d80de111d --- /dev/null +++ b/src/plugins/visualizations/server/usage_collector/get_past_days.ts @@ -0,0 +1,25 @@ +/* + * 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 const getPastDays = (dateString: string): number => { + const date = new Date(dateString); + const today = new Date(); + const diff = Math.abs(date.getTime() - today.getTime()); + return Math.trunc(diff / (1000 * 60 * 60 * 24)); +}; diff --git a/src/plugins/visualizations/server/usage_collector/get_usage_collector.test.ts b/src/plugins/visualizations/server/usage_collector/get_usage_collector.test.ts new file mode 100644 index 00000000000000..4a8e4b70ae070f --- /dev/null +++ b/src/plugins/visualizations/server/usage_collector/get_usage_collector.test.ts @@ -0,0 +1,195 @@ +/* + * 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 moment from 'moment'; +import { of } from 'rxjs'; + +import { LegacyAPICaller } from 'src/core/server'; +import { getUsageCollector } from './get_usage_collector'; + +const defaultMockSavedObjects = [ + { + _id: 'visualization:coolviz-123', + _source: { + type: 'visualization', + visualization: { visState: '{"type": "shell_beads"}' }, + updated_at: moment().subtract(7, 'days').startOf('day').toString(), + }, + }, +]; + +const enlargedMockSavedObjects = [ + // default space + { + _id: 'visualization:coolviz-123', + _source: { + type: 'visualization', + visualization: { visState: '{"type": "cave_painting"}' }, + updated_at: moment().subtract(7, 'days').startOf('day').toString(), + }, + }, + { + _id: 'visualization:coolviz-456', + _source: { + type: 'visualization', + visualization: { visState: '{"type": "printing_press"}' }, + updated_at: moment().subtract(20, 'days').startOf('day').toString(), + }, + }, + { + _id: 'meat:visualization:coolviz-789', + _source: { + type: 'visualization', + visualization: { visState: '{"type": "floppy_disk"}' }, + updated_at: moment().subtract(2, 'months').startOf('day').toString(), + }, + }, + // meat space + { + _id: 'meat:visualization:coolviz-789', + _source: { + type: 'visualization', + visualization: { visState: '{"type": "cave_painting"}' }, + updated_at: moment().subtract(89, 'days').startOf('day').toString(), + }, + }, + { + _id: 'meat:visualization:coolviz-789', + _source: { + type: 'visualization', + visualization: { visState: '{"type": "cuneiform"}' }, + updated_at: moment().subtract(5, 'months').startOf('day').toString(), + }, + }, + { + _id: 'meat:visualization:coolviz-789', + _source: { + type: 'visualization', + visualization: { visState: '{"type": "cuneiform"}' }, + updated_at: moment().subtract(2, 'days').startOf('day').toString(), + }, + }, + { + _id: 'meat:visualization:coolviz-789', + _source: { + type: 'visualization', + visualization: { visState: '{"type": "floppy_disk"}' }, + updated_at: moment().subtract(7, 'days').startOf('day').toString(), + }, + }, + // cyber space + { + _id: 'cyber:visualization:coolviz-789', + _source: { + type: 'visualization', + visualization: { visState: '{"type": "floppy_disk"}' }, + updated_at: moment().subtract(7, 'months').startOf('day').toString(), + }, + }, + { + _id: 'cyber:visualization:coolviz-789', + _source: { + type: 'visualization', + visualization: { visState: '{"type": "floppy_disk"}' }, + updated_at: moment().subtract(3, 'days').startOf('day').toString(), + }, + }, + { + _id: 'cyber:visualization:coolviz-123', + _source: { + type: 'visualization', + visualization: { visState: '{"type": "cave_painting"}' }, + updated_at: moment().subtract(15, 'days').startOf('day').toString(), + }, + }, +]; + +describe('Visualizations usage collector', () => { + const configMock = of({ kibana: { index: '' } }); + const usageCollector = getUsageCollector(configMock); + const getMockCallCluster = (hits: unknown[]) => + (() => Promise.resolve({ hits: { hits } }) as unknown) as LegacyAPICaller; + + test('Should fit the shape', () => { + expect(usageCollector.type).toBe('visualization_types'); + expect(usageCollector.isReady()).toBe(true); + expect(usageCollector.fetch).toEqual(expect.any(Function)); + }); + + test('Summarizes visualizations response data', async () => { + const result = await usageCollector.fetch(getMockCallCluster(defaultMockSavedObjects)); + + expect(result).toMatchObject({ + shell_beads: { + spaces_avg: 1, + spaces_max: 1, + spaces_min: 1, + total: 1, + saved_7_days_total: 1, + saved_30_days_total: 1, + saved_90_days_total: 1, + }, + }); + }); + + test('Summarizes visualizations response data per Space', async () => { + const expectedStats = { + cave_painting: { + total: 3, + spaces_min: 1, + spaces_max: 1, + spaces_avg: 1, + saved_7_days_total: 1, + saved_30_days_total: 2, + saved_90_days_total: 3, + }, + printing_press: { + total: 1, + spaces_min: 1, + spaces_max: 1, + spaces_avg: 1, + saved_7_days_total: 0, + saved_30_days_total: 1, + saved_90_days_total: 1, + }, + cuneiform: { + total: 2, + spaces_min: 2, + spaces_max: 2, + spaces_avg: 2, + saved_7_days_total: 1, + saved_30_days_total: 1, + saved_90_days_total: 1, + }, + floppy_disk: { + total: 4, + spaces_min: 2, + spaces_max: 2, + spaces_avg: 2, + saved_7_days_total: 2, + saved_30_days_total: 2, + saved_90_days_total: 3, + }, + }; + + const result = await usageCollector.fetch(getMockCallCluster(enlargedMockSavedObjects)); + + expect(result).toMatchObject(expectedStats); + }); +}); diff --git a/src/plugins/visualizations/server/usage_collector/get_usage_collector.ts b/src/plugins/visualizations/server/usage_collector/get_usage_collector.ts new file mode 100644 index 00000000000000..165c3ee649868a --- /dev/null +++ b/src/plugins/visualizations/server/usage_collector/get_usage_collector.ts @@ -0,0 +1,107 @@ +/* + * 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 { Observable } from 'rxjs'; +import { countBy, get, groupBy, mapValues, max, min, values } from 'lodash'; +import { first } from 'rxjs/operators'; +import { SearchResponse } from 'elasticsearch'; + +import { LegacyAPICaller } from 'src/core/server'; +import { getPastDays } from './get_past_days'; + +const VIS_USAGE_TYPE = 'visualization_types'; + +type ESResponse = SearchResponse<{ visualization: { visState: string } }>; + +interface VisSummary { + type: string; + space: string; + past_days: number; +} + +/* + * Parse the response data into telemetry payload + */ +async function getStats(callCluster: LegacyAPICaller, index: string) { + const searchParams = { + size: 10000, // elasticsearch index.max_result_window default value + index, + ignoreUnavailable: true, + filterPath: [ + 'hits.hits._id', + 'hits.hits._source.visualization', + 'hits.hits._source.updated_at', + ], + body: { + query: { + bool: { filter: { term: { type: 'visualization' } } }, + }, + }, + }; + const esResponse: ESResponse = await callCluster('search', searchParams); + const size = get(esResponse, 'hits.hits.length'); + if (size < 1) { + return; + } + + // `map` to get the raw types + const visSummaries: VisSummary[] = esResponse.hits.hits.map((hit) => { + const spacePhrases = hit._id.split(':'); + const lastUpdated: string = get(hit, '_source.updated_at'); + const space = spacePhrases.length === 3 ? spacePhrases[0] : 'default'; // if in a custom space, the format of a saved object ID is space:type:id + const visualization = get(hit, '_source.visualization', { visState: '{}' }); + const visState: { type?: string } = JSON.parse(visualization.visState); + return { + type: visState.type || '_na_', + space, + past_days: getPastDays(lastUpdated), + }; + }); + + // organize stats per type + const visTypes = groupBy(visSummaries, 'type'); + + // get the final result + return mapValues(visTypes, (curr) => { + const total = curr.length; + const spacesBreakdown = countBy(curr, 'space'); + const spaceCounts: number[] = values(spacesBreakdown); + + return { + total, + spaces_min: min(spaceCounts), + spaces_max: max(spaceCounts), + spaces_avg: total / spaceCounts.length, + saved_7_days_total: curr.filter((c) => c.past_days <= 7).length, + saved_30_days_total: curr.filter((c) => c.past_days <= 30).length, + saved_90_days_total: curr.filter((c) => c.past_days <= 90).length, + }; + }); +} + +export function getUsageCollector(config: Observable<{ kibana: { index: string } }>) { + return { + type: VIS_USAGE_TYPE, + isReady: () => true, + fetch: async (callCluster: LegacyAPICaller) => { + const index = (await config.pipe(first()).toPromise()).kibana.index; + return await getStats(callCluster, index); + }, + }; +} diff --git a/src/plugins/visualizations/server/usage_collector/index.ts b/src/plugins/visualizations/server/usage_collector/index.ts new file mode 100644 index 00000000000000..90ee65bb6ad2a5 --- /dev/null +++ b/src/plugins/visualizations/server/usage_collector/index.ts @@ -0,0 +1,31 @@ +/* + * 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 { Observable } from 'rxjs'; + +import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; +import { getUsageCollector } from './get_usage_collector'; + +export function registerVisualizationsCollector( + collectorSet: UsageCollectionSetup, + config: Observable<{ kibana: { index: string } }> +): void { + const collector = collectorSet.makeUsageCollector(getUsageCollector(config)); + collectorSet.registerCollector(collector); +} diff --git a/x-pack/plugins/oss_telemetry/constants.ts b/x-pack/plugins/oss_telemetry/constants.ts deleted file mode 100644 index 1e83bff092f2c1..00000000000000 --- a/x-pack/plugins/oss_telemetry/constants.ts +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -export const PLUGIN_ID = 'oss_telemetry'; // prefix used for registering properties with services from this plugin -export const VIS_TELEMETRY_TASK = 'vis_telemetry'; // suffix for the _id of our task instance, which must be `get`-able -export const VIS_USAGE_TYPE = 'visualization_types'; // suffix for the properties of data registered with the usage service diff --git a/x-pack/plugins/oss_telemetry/kibana.json b/x-pack/plugins/oss_telemetry/kibana.json deleted file mode 100644 index 0defee0881e0e6..00000000000000 --- a/x-pack/plugins/oss_telemetry/kibana.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "id": "ossTelemetry", - "server": true, - "version": "8.0.0", - "kibanaVersion": "kibana", - "requiredPlugins": ["usageCollection", "taskManager"], - "configPath": ["xpack", "oss_telemetry"], - "ui": false -} diff --git a/x-pack/plugins/oss_telemetry/server/index.ts b/x-pack/plugins/oss_telemetry/server/index.ts deleted file mode 100644 index 64527ca6daa7ed..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { PluginInitializerContext } from 'src/core/server'; -import { OssTelemetryPlugin } from './plugin'; - -export const plugin = (context: PluginInitializerContext) => new OssTelemetryPlugin(context); - -export * from './plugin'; diff --git a/x-pack/plugins/oss_telemetry/server/lib/collectors/index.ts b/x-pack/plugins/oss_telemetry/server/lib/collectors/index.ts deleted file mode 100644 index 845e11b80af0ef..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/lib/collectors/index.ts +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { registerVisualizationsCollector } from './visualizations/register_usage_collector'; -import { UsageCollectionSetup } from '../../../../../../src/plugins/usage_collection/server'; -import { TaskManagerStartContract } from '../../../../task_manager/server'; - -export function registerCollectors( - usageCollection: UsageCollectionSetup, - taskManager: Promise -) { - registerVisualizationsCollector(usageCollection, taskManager); -} diff --git a/x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/get_usage_collector.test.ts b/x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/get_usage_collector.test.ts deleted file mode 100644 index 43114787b40e5d..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/get_usage_collector.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { - getMockTaskFetch, - getMockThrowingTaskFetch, - getMockTaskInstance, -} from '../../../test_utils'; -import { taskManagerMock } from '../../../../../task_manager/server/task_manager.mock'; -import { getUsageCollector } from './get_usage_collector'; - -describe('getVisualizationsCollector#fetch', () => { - test('can return empty stats', async () => { - const { type, fetch } = getUsageCollector( - Promise.resolve(taskManagerMock.start(getMockTaskFetch())) - ); - expect(type).toBe('visualization_types'); - const fetchResult = await fetch(); - expect(fetchResult).toEqual({}); - }); - - test('provides known stats', async () => { - const { type, fetch } = getUsageCollector( - Promise.resolve( - taskManagerMock.start( - getMockTaskFetch([ - getMockTaskInstance({ - state: { - runs: 1, - stats: { comic_books: { total: 16, max: 12, min: 2, avg: 6 } }, - }, - taskType: 'test', - params: {}, - }), - ]) - ) - ) - ); - expect(type).toBe('visualization_types'); - const fetchResult = await fetch(); - expect(fetchResult).toEqual({ comic_books: { avg: 6, max: 12, min: 2, total: 16 } }); - }); - - describe('Error handling', () => { - test('Silently handles Task Manager NotInitialized', async () => { - const { fetch } = getUsageCollector( - Promise.resolve( - taskManagerMock.start( - getMockThrowingTaskFetch( - new Error('NotInitialized taskManager is still waiting for plugins to load') - ) - ) - ) - ); - const result = await fetch(); - expect(result).toBe(undefined); - }); - // In real life, the CollectorSet calls fetch and handles errors - test('defers the errors', async () => { - const { fetch } = getUsageCollector( - Promise.resolve(taskManagerMock.start(getMockThrowingTaskFetch(new Error('BOOM')))) - ); - await expect(fetch()).rejects.toThrowErrorMatchingInlineSnapshot(`"BOOM"`); - }); - }); -}); diff --git a/x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/get_usage_collector.ts b/x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/get_usage_collector.ts deleted file mode 100644 index 9828dea4c93934..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/get_usage_collector.ts +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { get } from 'lodash'; -import { PLUGIN_ID, VIS_TELEMETRY_TASK, VIS_USAGE_TYPE } from '../../../../constants'; -import { TaskManagerStartContract } from '../../../../../task_manager/server'; - -async function fetch(taskManager: TaskManagerStartContract) { - let docs; - try { - ({ docs } = await taskManager.fetch({ - query: { bool: { filter: { term: { _id: `task:${PLUGIN_ID}-${VIS_TELEMETRY_TASK}` } } } }, - })); - } catch (err) { - const errMessage = err && err.message ? err.message : err.toString(); - /* - The usage service WILL to try to fetch from this collector before the task manager has been initialized, because the task manager has to wait for all plugins to initialize first. It's fine to ignore it as next time around it will be initialized (or it will throw a different type of error) - */ - if (errMessage.includes('NotInitialized')) { - docs = null; - } else { - throw err; - } - } - - return docs; -} - -export function getUsageCollector(taskManager: Promise) { - return { - type: VIS_USAGE_TYPE, - isReady: () => true, - fetch: async () => { - const docs = await fetch(await taskManager); - // get the accumulated state from the recurring task - return get(docs, '[0].state.stats'); - }, - }; -} diff --git a/x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/register_usage_collector.ts b/x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/register_usage_collector.ts deleted file mode 100644 index 667e8b9b875fdb..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/lib/collectors/visualizations/register_usage_collector.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; -import { TaskManagerStartContract } from '../../../../../task_manager/server'; -import { getUsageCollector } from './get_usage_collector'; - -export function registerVisualizationsCollector( - collectorSet: UsageCollectionSetup, - taskManager: Promise -): void { - const collector = collectorSet.makeUsageCollector(getUsageCollector(taskManager)); - collectorSet.registerCollector(collector); -} diff --git a/x-pack/plugins/oss_telemetry/server/lib/get_next_midnight.test.ts b/x-pack/plugins/oss_telemetry/server/lib/get_next_midnight.test.ts deleted file mode 100644 index 3bafb84d61157c..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/lib/get_next_midnight.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import moment from 'moment'; -import { getNextMidnight } from './get_next_midnight'; - -describe('getNextMidnight', () => { - test('Returns the next time and date of midnight as an iso string', () => { - const nextMidnightMoment = moment().add(1, 'days').startOf('day').toDate(); - - expect(getNextMidnight()).toEqual(nextMidnightMoment); - }); -}); diff --git a/x-pack/plugins/oss_telemetry/server/lib/get_next_midnight.ts b/x-pack/plugins/oss_telemetry/server/lib/get_next_midnight.ts deleted file mode 100644 index a5ee8d572343ce..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/lib/get_next_midnight.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -export function getNextMidnight() { - const nextMidnight = new Date(); - nextMidnight.setHours(0, 0, 0, 0); - nextMidnight.setDate(nextMidnight.getDate() + 1); - return nextMidnight; -} diff --git a/x-pack/plugins/oss_telemetry/server/lib/get_past_days.test.ts b/x-pack/plugins/oss_telemetry/server/lib/get_past_days.test.ts deleted file mode 100644 index 28909779343a54..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/lib/get_past_days.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import moment from 'moment'; -import { getPastDays } from './get_past_days'; - -describe('getPastDays', () => { - test('Returns 2 days that have passed from the current date', () => { - const pastDate = moment().subtract(2, 'days').startOf('day').toString(); - - expect(getPastDays(pastDate)).toEqual(2); - }); - - test('Returns 30 days that have passed from the current date', () => { - const pastDate = moment().subtract(30, 'days').startOf('day').toString(); - - expect(getPastDays(pastDate)).toEqual(30); - }); -}); diff --git a/x-pack/plugins/oss_telemetry/server/lib/get_past_days.ts b/x-pack/plugins/oss_telemetry/server/lib/get_past_days.ts deleted file mode 100644 index 4f25ef147ad43d..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/lib/get_past_days.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -export const getPastDays = (dateString: string): number => { - const date = new Date(dateString); - const today = new Date(); - const diff = Math.abs(date.getTime() - today.getTime()); - return Math.trunc(diff / (1000 * 60 * 60 * 24)); -}; diff --git a/x-pack/plugins/oss_telemetry/server/lib/tasks/index.ts b/x-pack/plugins/oss_telemetry/server/lib/tasks/index.ts deleted file mode 100644 index 415aeb2791d9eb..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/lib/tasks/index.ts +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { Observable } from 'rxjs'; -import { CoreSetup, Logger } from 'kibana/server'; -import { PLUGIN_ID, VIS_TELEMETRY_TASK } from '../../../constants'; -import { visualizationsTaskRunner } from './visualizations/task_runner'; -import { - TaskInstance, - TaskManagerStartContract, - TaskManagerSetupContract, -} from '../../../../task_manager/server'; - -export function registerTasks({ - taskManager, - logger, - getStartServices, - config, -}: { - taskManager?: TaskManagerSetupContract; - logger: Logger; - getStartServices: CoreSetup['getStartServices']; - config: Observable<{ kibana: { index: string } }>; -}) { - if (!taskManager) { - logger.debug('Task manager is not available'); - return; - } - - const esClientPromise = getStartServices().then( - ([{ elasticsearch }]) => elasticsearch.legacy.client - ); - - taskManager.registerTaskDefinitions({ - [VIS_TELEMETRY_TASK]: { - title: 'X-Pack telemetry calculator for Visualizations', - type: VIS_TELEMETRY_TASK, - createTaskRunner({ taskInstance }: { taskInstance: TaskInstance }) { - return { - run: visualizationsTaskRunner(taskInstance, config, esClientPromise), - cancel: async () => {}, - }; - }, - }, - }); -} - -export async function scheduleTasks({ - taskManager, - logger, -}: { - taskManager?: TaskManagerStartContract; - logger: Logger; -}) { - if (!taskManager) { - logger.debug('Task manager is not available'); - return; - } - - try { - await taskManager.ensureScheduled({ - id: `${PLUGIN_ID}-${VIS_TELEMETRY_TASK}`, - taskType: VIS_TELEMETRY_TASK, - state: { stats: {}, runs: 0 }, - params: {}, - }); - } catch (e) { - logger.debug(`Error scheduling task, received ${e.message}`); - } -} diff --git a/x-pack/plugins/oss_telemetry/server/lib/tasks/visualizations/task_runner.test.ts b/x-pack/plugins/oss_telemetry/server/lib/tasks/visualizations/task_runner.test.ts deleted file mode 100644 index c064f39f4bc6a6..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/lib/tasks/visualizations/task_runner.test.ts +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { - getMockCallWithInternal, - getMockConfig, - getMockEs, - getMockTaskInstance, -} from '../../../test_utils'; -import { visualizationsTaskRunner } from './task_runner'; -import { TaskInstance } from '../../../../../task_manager/server'; -import { getNextMidnight } from '../../get_next_midnight'; -import moment from 'moment'; - -describe('visualizationsTaskRunner', () => { - let mockTaskInstance: TaskInstance; - beforeEach(() => { - mockTaskInstance = getMockTaskInstance(); - }); - - describe('Error handling', () => { - test('catches its own errors', async () => { - const mockCallWithInternal = () => Promise.reject(new Error('Things did not go well!')); - - const runner = visualizationsTaskRunner( - mockTaskInstance, - getMockConfig(), - getMockEs(mockCallWithInternal) - ); - const result = await runner(); - expect(result).toMatchObject({ - error: 'Things did not go well!', - state: { - runs: 1, - stats: undefined, - }, - }); - }); - }); - - test('Summarizes visualization response data', async () => { - const runner = visualizationsTaskRunner(mockTaskInstance, getMockConfig(), getMockEs()); - const result = await runner(); - - expect(result).toMatchObject({ - error: undefined, - runAt: getNextMidnight(), - state: { - runs: 1, - stats: { - shell_beads: { - spaces_avg: 1, - spaces_max: 1, - spaces_min: 1, - total: 1, - saved_7_days_total: 1, - saved_30_days_total: 1, - saved_90_days_total: 1, - }, - }, - }, - }); - }); - - test('Summarizes visualization response data per Space', async () => { - const mockCallWithInternal = getMockCallWithInternal([ - // default space - { - _id: 'visualization:coolviz-123', - _source: { - type: 'visualization', - visualization: { visState: '{"type": "cave_painting"}' }, - updated_at: moment().subtract(7, 'days').startOf('day').toString(), - }, - }, - { - _id: 'visualization:coolviz-456', - _source: { - type: 'visualization', - visualization: { visState: '{"type": "printing_press"}' }, - updated_at: moment().subtract(20, 'days').startOf('day').toString(), - }, - }, - { - _id: 'meat:visualization:coolviz-789', - _source: { - type: 'visualization', - visualization: { visState: '{"type": "floppy_disk"}' }, - updated_at: moment().subtract(2, 'months').startOf('day').toString(), - }, - }, - // meat space - { - _id: 'meat:visualization:coolviz-789', - _source: { - type: 'visualization', - visualization: { visState: '{"type": "cave_painting"}' }, - updated_at: moment().subtract(89, 'days').startOf('day').toString(), - }, - }, - { - _id: 'meat:visualization:coolviz-789', - _source: { - type: 'visualization', - visualization: { visState: '{"type": "cuneiform"}' }, - updated_at: moment().subtract(5, 'months').startOf('day').toString(), - }, - }, - { - _id: 'meat:visualization:coolviz-789', - _source: { - type: 'visualization', - visualization: { visState: '{"type": "cuneiform"}' }, - updated_at: moment().subtract(2, 'days').startOf('day').toString(), - }, - }, - { - _id: 'meat:visualization:coolviz-789', - _source: { - type: 'visualization', - visualization: { visState: '{"type": "floppy_disk"}' }, - updated_at: moment().subtract(7, 'days').startOf('day').toString(), - }, - }, - // cyber space - { - _id: 'cyber:visualization:coolviz-789', - _source: { - type: 'visualization', - visualization: { visState: '{"type": "floppy_disk"}' }, - updated_at: moment().subtract(7, 'months').startOf('day').toString(), - }, - }, - { - _id: 'cyber:visualization:coolviz-789', - _source: { - type: 'visualization', - visualization: { visState: '{"type": "floppy_disk"}' }, - updated_at: moment().subtract(3, 'days').startOf('day').toString(), - }, - }, - { - _id: 'cyber:visualization:coolviz-123', - _source: { - type: 'visualization', - visualization: { visState: '{"type": "cave_painting"}' }, - updated_at: moment().subtract(15, 'days').startOf('day').toString(), - }, - }, - ]); - - const expectedStats = { - cave_painting: { - total: 3, - spaces_min: 1, - spaces_max: 1, - spaces_avg: 1, - saved_7_days_total: 1, - saved_30_days_total: 2, - saved_90_days_total: 3, - }, - printing_press: { - total: 1, - spaces_min: 1, - spaces_max: 1, - spaces_avg: 1, - saved_7_days_total: 0, - saved_30_days_total: 1, - saved_90_days_total: 1, - }, - cuneiform: { - total: 2, - spaces_min: 2, - spaces_max: 2, - spaces_avg: 2, - saved_7_days_total: 1, - saved_30_days_total: 1, - saved_90_days_total: 1, - }, - floppy_disk: { - total: 4, - spaces_min: 2, - spaces_max: 2, - spaces_avg: 2, - saved_7_days_total: 2, - saved_30_days_total: 2, - saved_90_days_total: 3, - }, - }; - - const runner = visualizationsTaskRunner( - mockTaskInstance, - getMockConfig(), - getMockEs(mockCallWithInternal) - ); - const result = await runner(); - - expect(result).toMatchObject({ - error: undefined, - state: { - runs: 1, - stats: expectedStats, - }, - }); - - expect(result.state.stats).toMatchObject(expectedStats); - }); -}); diff --git a/x-pack/plugins/oss_telemetry/server/lib/tasks/visualizations/task_runner.ts b/x-pack/plugins/oss_telemetry/server/lib/tasks/visualizations/task_runner.ts deleted file mode 100644 index 27913fafe32572..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/lib/tasks/visualizations/task_runner.ts +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { Observable } from 'rxjs'; -import _, { countBy, groupBy, mapValues } from 'lodash'; -import { first } from 'rxjs/operators'; - -import { LegacyAPICaller, ILegacyClusterClient } from 'src/core/server'; -import { getNextMidnight } from '../../get_next_midnight'; -import { getPastDays } from '../../get_past_days'; -import { TaskInstance } from '../../../../../task_manager/server'; -import { ESSearchHit } from '../../../../../apm/typings/elasticsearch'; - -interface VisSummary { - type: string; - space: string; - past_days: number; -} - -/* - * Parse the response data into telemetry payload - */ -async function getStats(callCluster: LegacyAPICaller, index: string) { - const searchParams = { - size: 10000, // elasticsearch index.max_result_window default value - index, - ignoreUnavailable: true, - filterPath: [ - 'hits.hits._id', - 'hits.hits._source.visualization', - 'hits.hits._source.updated_at', - ], - body: { - query: { - bool: { filter: { term: { type: 'visualization' } } }, - }, - }, - }; - const esResponse = await callCluster('search', searchParams); - const size = _.get(esResponse, 'hits.hits.length') as number; - if (size < 1) { - return; - } - - // `map` to get the raw types - const visSummaries: VisSummary[] = esResponse.hits.hits.map( - (hit: ESSearchHit<{ visState: string }>) => { - const spacePhrases: string[] = hit._id.split(':'); - const lastUpdated: string = _.get(hit, '_source.updated_at'); - const space = spacePhrases.length === 3 ? spacePhrases[0] : 'default'; // if in a custom space, the format of a saved object ID is space:type:id - const visualization = _.get(hit, '_source.visualization', { visState: '{}' }); - const visState: { type?: string } = JSON.parse(visualization.visState); - return { - type: visState.type || '_na_', - space, - past_days: getPastDays(lastUpdated), - }; - } - ); - - // organize stats per type - const visTypes = groupBy(visSummaries, 'type'); - - // get the final result - return mapValues(visTypes, (curr) => { - const total = curr.length; - const spacesBreakdown = countBy(curr, 'space'); - const spaceCounts: number[] = _.values(spacesBreakdown); - - return { - total, - spaces_min: _.min(spaceCounts), - spaces_max: _.max(spaceCounts), - spaces_avg: total / spaceCounts.length, - saved_7_days_total: curr.filter((c) => c.past_days <= 7).length, - saved_30_days_total: curr.filter((c) => c.past_days <= 30).length, - saved_90_days_total: curr.filter((c) => c.past_days <= 90).length, - }; - }); -} - -export function visualizationsTaskRunner( - taskInstance: TaskInstance, - config: Observable<{ kibana: { index: string } }>, - esClientPromise: Promise -) { - return async () => { - let stats; - let error; - - try { - const index = (await config.pipe(first()).toPromise()).kibana.index; - stats = await getStats((await esClientPromise).callAsInternalUser, index); - } catch (err) { - if (err.constructor === Error) { - error = err.message; - } else { - error = err; - } - } - - return { - runAt: getNextMidnight(), - state: { - runs: taskInstance.state.runs + 1, - stats, - }, - error, - }; - }; -} diff --git a/x-pack/plugins/oss_telemetry/server/plugin.ts b/x-pack/plugins/oss_telemetry/server/plugin.ts deleted file mode 100644 index 6a447da66952a4..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/plugin.ts +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { Observable } from 'rxjs'; -import { CoreSetup, CoreStart, Logger, Plugin, PluginInitializerContext } from 'kibana/server'; -import { TaskManagerSetupContract, TaskManagerStartContract } from '../../task_manager/server'; -import { registerCollectors } from './lib/collectors'; -import { registerTasks, scheduleTasks } from './lib/tasks'; -import { UsageCollectionSetup } from '../../../../src/plugins/usage_collection/server'; - -export interface OssTelemetrySetupDependencies { - usageCollection: UsageCollectionSetup; - taskManager: TaskManagerSetupContract; -} -export interface OssTelemetryStartDependencies { - taskManager: TaskManagerStartContract; -} - -export class OssTelemetryPlugin implements Plugin { - private readonly logger: Logger; - private readonly config: Observable<{ kibana: { index: string } }>; - - constructor(initializerContext: PluginInitializerContext) { - this.logger = initializerContext.logger.get('oss_telemetry'); - this.config = initializerContext.config.legacy.globalConfig$; - } - - public setup( - core: CoreSetup, - deps: OssTelemetrySetupDependencies - ) { - registerTasks({ - taskManager: deps.taskManager, - logger: this.logger, - getStartServices: core.getStartServices, - config: this.config, - }); - registerCollectors( - deps.usageCollection, - core.getStartServices().then(([_, { taskManager }]) => taskManager) - ); - } - - public start(core: CoreStart, deps: OssTelemetryStartDependencies) { - scheduleTasks({ - taskManager: deps.taskManager, - logger: this.logger, - }); - } -} diff --git a/x-pack/plugins/oss_telemetry/server/test_utils/index.ts b/x-pack/plugins/oss_telemetry/server/test_utils/index.ts deleted file mode 100644 index 9201899d5a161a..00000000000000 --- a/x-pack/plugins/oss_telemetry/server/test_utils/index.ts +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { LegacyAPICaller } from 'kibana/server'; - -import { of } from 'rxjs'; -import moment from 'moment'; -import { elasticsearchServiceMock } from '../../../../../src/core/server/mocks'; -import { - ConcreteTaskInstance, - TaskStatus, - TaskManagerStartContract, -} from '../../../task_manager/server'; - -export const getMockTaskInstance = ( - overrides: Partial = {} -): ConcreteTaskInstance => ({ - state: { runs: 0, stats: {} }, - taskType: 'test', - params: {}, - id: '', - scheduledAt: new Date(), - attempts: 1, - status: TaskStatus.Idle, - runAt: new Date(), - startedAt: null, - retryAt: null, - ownerId: null, - ...overrides, -}); - -const defaultMockSavedObjects = [ - { - _id: 'visualization:coolviz-123', - _source: { - type: 'visualization', - visualization: { visState: '{"type": "shell_beads"}' }, - updated_at: moment().subtract(7, 'days').startOf('day').toString(), - }, - }, -]; - -const defaultMockTaskDocs = [getMockTaskInstance()]; - -export const getMockEs = async ( - mockCallWithInternal: LegacyAPICaller = getMockCallWithInternal() -) => { - const client = elasticsearchServiceMock.createLegacyClusterClient(); - (client.callAsInternalUser as any) = mockCallWithInternal; - return client; -}; - -export const getMockCallWithInternal = ( - hits: unknown[] = defaultMockSavedObjects -): LegacyAPICaller => { - return ((() => { - return Promise.resolve({ hits: { hits } }); - }) as unknown) as LegacyAPICaller; -}; - -export const getMockTaskFetch = ( - docs: ConcreteTaskInstance[] = defaultMockTaskDocs -): Partial> => { - return { - fetch: jest.fn((fetchOpts) => { - return Promise.resolve({ docs, searchAfter: [] }); - }), - } as Partial>; -}; - -export const getMockThrowingTaskFetch = ( - throws: Error -): Partial> => { - return { - fetch: jest.fn((fetchOpts) => { - throw throws; - }), - } as Partial>; -}; - -export const getMockConfig = () => { - return of({ kibana: { index: '' } }); -}; - -export const getCluster = () => ({ - callWithInternalUser: getMockCallWithInternal(), -}); From 1ea61ec478cf24e9a36fb434c43ff45022b394a3 Mon Sep 17 00:00:00 2001 From: Jean-Louis Leysens Date: Mon, 14 Sep 2020 12:45:08 +0200 Subject: [PATCH 2/6] fix double hline under drop processor (#76929) Co-authored-by: Elastic Machine --- .../manage_processor_form/processor_settings_fields.tsx | 6 +++--- .../components/manage_processor_form/processors/drop.tsx | 6 +----- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/manage_processor_form/processor_settings_fields.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/manage_processor_form/processor_settings_fields.tsx index bda64c0a756126..bdd3d87aec6cd6 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/manage_processor_form/processor_settings_fields.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/manage_processor_form/processor_settings_fields.tsx @@ -32,13 +32,13 @@ export const ProcessorSettingsFields: FunctionComponent = ({ processor }) if (type?.length) { const formDescriptor = getProcessorDescriptor(type as any); - if (formDescriptor?.FieldsComponent) { - const renderedFields = ( + if (formDescriptor) { + const renderedFields = formDescriptor.FieldsComponent ? ( - ); + ) : null; return ( <> {renderedFields ? ( diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/manage_processor_form/processors/drop.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/manage_processor_form/processors/drop.tsx index 87b6cb76cdccec..7bc299532df9ef 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/manage_processor_form/processors/drop.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/manage_processor_form/processors/drop.tsx @@ -4,11 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { FunctionComponent } from 'react'; - /** * This fields component has no unique fields */ -export const Drop: FunctionComponent = () => { - return null; -}; +export const Drop = undefined; From 97813b29dd630ea4b9e068b26b5ed843312b6ca5 Mon Sep 17 00:00:00 2001 From: Jean-Louis Leysens Date: Mon, 14 Sep 2020 12:46:12 +0200 Subject: [PATCH 3/6] [Ingest Pipelines] Drop into an empty tree (#76885) * add ability to drop processor into empty tree * added a test Co-authored-by: Elastic Machine --- .../pipeline_processors_editor.test.tsx | 9 +++++++ .../components/add_processor_button.tsx | 1 + .../processors_tree/processors_tree.scss | 4 +++ .../processors_tree/processors_tree.tsx | 27 ++++++++++++++++--- 4 files changed, 37 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/__jest__/pipeline_processors_editor.test.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/__jest__/pipeline_processors_editor.test.tsx index b12f3245281676..38c652f41e5e17 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/__jest__/pipeline_processors_editor.test.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/__jest__/pipeline_processors_editor.test.tsx @@ -184,5 +184,14 @@ describe('Pipeline Editor', () => { expect(find('processors>0.moveItemButton').props().disabled).toBe(true); expect(find('processors>1.moveItemButton').props().disabled).toBe(true); }); + + it('can move a processor into an empty tree', () => { + const { actions } = testBed; + actions.moveProcessor('processors>0', 'onFailure.dropButtonEmptyTree'); + const [onUpdateResult2] = onUpdate.mock.calls[onUpdate.mock.calls.length - 1]; + const data = onUpdateResult2.getData(); + expect(data.processors).toEqual([testProcessors.processors[1]]); + expect(data.on_failure).toEqual([testProcessors.processors[0]]); + }); }); }); diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/add_processor_button.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/add_processor_button.tsx index 276d684e3dca14..4aabcc1d59d730 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/add_processor_button.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_processors_editor/components/add_processor_button.tsx @@ -21,6 +21,7 @@ export const AddProcessorButton: FunctionComponent = (props) => { return ( = memo((props) => { /> - - + + + {!processors.length && ( + { + event.preventDefault(); + onAction({ + type: 'move', + payload: { + destination: baseSelector.concat(DropSpecialLocations.top), + source: movingProcessor!.selector, + }, + }); + }} + /> + )} { onAction({ type: 'addProcessor', payload: { target: baseSelector } }); From 02e10a04f28f16e513ae938f053e54a8b7cba288 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B8ren=20Louv-Jansen?= Date: Mon, 14 Sep 2020 12:47:55 +0200 Subject: [PATCH 4/6] Fix APM issue template --- .github/ISSUE_TEMPLATE/APM.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/APM.md b/.github/ISSUE_TEMPLATE/APM.md index 983806f70bc3fa..c3abbdd67269de 100644 --- a/.github/ISSUE_TEMPLATE/APM.md +++ b/.github/ISSUE_TEMPLATE/APM.md @@ -2,7 +2,7 @@ name: APM Issue about: Issues related to the APM solution in Kibana labels: Team:apm -title: [APM] +title: "[APM]" --- **Versions** From 4a45dad51fe714c0ccfb5fa8a9754c2ef1c38530 Mon Sep 17 00:00:00 2001 From: Anton Dosov Date: Mon, 14 Sep 2020 12:58:22 +0200 Subject: [PATCH 5/6] [Drilldowns] Wire up new links to new docs (#77154) Co-authored-by: Elastic Machine --- .../kibana-plugin-core-public.doclinksstart.links.md | 3 +++ .../public/kibana-plugin-core-public.doclinksstart.md | 2 +- src/core/public/doc_links/doc_links_service.ts | 6 ++++++ src/core/public/public.api.md | 3 +++ .../drilldowns/url_drilldown/url_drilldown.test.ts | 1 + .../public/drilldowns/url_drilldown/url_drilldown.tsx | 2 ++ x-pack/plugins/embeddable_enhanced/public/plugin.ts | 5 ++++- .../connected_flyout_manage_drilldowns.tsx | 3 +++ .../flyout_drilldown_wizard.tsx | 11 ++++++++++- .../url_drilldown_collect_config.tsx | 4 +++- x-pack/plugins/ui_actions_enhanced/public/plugin.ts | 1 + 11 files changed, 37 insertions(+), 4 deletions(-) diff --git a/docs/development/core/public/kibana-plugin-core-public.doclinksstart.links.md b/docs/development/core/public/kibana-plugin-core-public.doclinksstart.links.md index 85e1da08b00afe..f7b55b0650d8b8 100644 --- a/docs/development/core/public/kibana-plugin-core-public.doclinksstart.links.md +++ b/docs/development/core/public/kibana-plugin-core-public.doclinksstart.links.md @@ -10,6 +10,9 @@ readonly links: { readonly dashboard: { readonly drilldowns: string; + readonly drilldownsTriggerPicker: string; + readonly urlDrilldownTemplateSyntax: string; + readonly urlDrilldownVariables: string; }; readonly filebeat: { readonly base: string; diff --git a/docs/development/core/public/kibana-plugin-core-public.doclinksstart.md b/docs/development/core/public/kibana-plugin-core-public.doclinksstart.md index 4644dc432bc9a9..3f58cf08ee6b6c 100644 --- a/docs/development/core/public/kibana-plugin-core-public.doclinksstart.md +++ b/docs/development/core/public/kibana-plugin-core-public.doclinksstart.md @@ -17,5 +17,5 @@ export interface DocLinksStart | --- | --- | --- | | [DOC\_LINK\_VERSION](./kibana-plugin-core-public.doclinksstart.doc_link_version.md) | string | | | [ELASTIC\_WEBSITE\_URL](./kibana-plugin-core-public.doclinksstart.elastic_website_url.md) | string | | -| [links](./kibana-plugin-core-public.doclinksstart.links.md) | {
readonly dashboard: {
readonly drilldowns: string;
};
readonly filebeat: {
readonly base: string;
readonly installation: string;
readonly configuration: string;
readonly elasticsearchOutput: string;
readonly startup: string;
readonly exportedFields: string;
};
readonly auditbeat: {
readonly base: string;
};
readonly metricbeat: {
readonly base: string;
};
readonly heartbeat: {
readonly base: string;
};
readonly logstash: {
readonly base: string;
};
readonly functionbeat: {
readonly base: string;
};
readonly winlogbeat: {
readonly base: string;
};
readonly aggs: {
readonly date_histogram: string;
readonly date_range: string;
readonly filter: string;
readonly filters: string;
readonly geohash_grid: string;
readonly histogram: string;
readonly ip_range: string;
readonly range: string;
readonly significant_terms: string;
readonly terms: string;
readonly avg: string;
readonly avg_bucket: string;
readonly max_bucket: string;
readonly min_bucket: string;
readonly sum_bucket: string;
readonly cardinality: string;
readonly count: string;
readonly cumulative_sum: string;
readonly derivative: string;
readonly geo_bounds: string;
readonly geo_centroid: string;
readonly max: string;
readonly median: string;
readonly min: string;
readonly moving_avg: string;
readonly percentile_ranks: string;
readonly serial_diff: string;
readonly std_dev: string;
readonly sum: string;
readonly top_hits: string;
};
readonly scriptedFields: {
readonly scriptFields: string;
readonly scriptAggs: string;
readonly painless: string;
readonly painlessApi: string;
readonly painlessSyntax: string;
readonly luceneExpressions: string;
};
readonly indexPatterns: {
readonly loadingData: string;
readonly introduction: string;
};
readonly addData: string;
readonly kibana: string;
readonly siem: {
readonly guide: string;
readonly gettingStarted: string;
};
readonly query: {
readonly luceneQuerySyntax: string;
readonly queryDsl: string;
readonly kueryQuerySyntax: string;
};
readonly date: {
readonly dateMath: string;
};
readonly management: Record<string, string>;
readonly visualize: Record<string, string>;
} | | +| [links](./kibana-plugin-core-public.doclinksstart.links.md) | {
readonly dashboard: {
readonly drilldowns: string;
readonly drilldownsTriggerPicker: string;
readonly urlDrilldownTemplateSyntax: string;
readonly urlDrilldownVariables: string;
};
readonly filebeat: {
readonly base: string;
readonly installation: string;
readonly configuration: string;
readonly elasticsearchOutput: string;
readonly startup: string;
readonly exportedFields: string;
};
readonly auditbeat: {
readonly base: string;
};
readonly metricbeat: {
readonly base: string;
};
readonly heartbeat: {
readonly base: string;
};
readonly logstash: {
readonly base: string;
};
readonly functionbeat: {
readonly base: string;
};
readonly winlogbeat: {
readonly base: string;
};
readonly aggs: {
readonly date_histogram: string;
readonly date_range: string;
readonly filter: string;
readonly filters: string;
readonly geohash_grid: string;
readonly histogram: string;
readonly ip_range: string;
readonly range: string;
readonly significant_terms: string;
readonly terms: string;
readonly avg: string;
readonly avg_bucket: string;
readonly max_bucket: string;
readonly min_bucket: string;
readonly sum_bucket: string;
readonly cardinality: string;
readonly count: string;
readonly cumulative_sum: string;
readonly derivative: string;
readonly geo_bounds: string;
readonly geo_centroid: string;
readonly max: string;
readonly median: string;
readonly min: string;
readonly moving_avg: string;
readonly percentile_ranks: string;
readonly serial_diff: string;
readonly std_dev: string;
readonly sum: string;
readonly top_hits: string;
};
readonly scriptedFields: {
readonly scriptFields: string;
readonly scriptAggs: string;
readonly painless: string;
readonly painlessApi: string;
readonly painlessSyntax: string;
readonly luceneExpressions: string;
};
readonly indexPatterns: {
readonly loadingData: string;
readonly introduction: string;
};
readonly addData: string;
readonly kibana: string;
readonly siem: {
readonly guide: string;
readonly gettingStarted: string;
};
readonly query: {
readonly luceneQuerySyntax: string;
readonly queryDsl: string;
readonly kueryQuerySyntax: string;
};
readonly date: {
readonly dateMath: string;
};
readonly management: Record<string, string>;
readonly visualize: Record<string, string>;
} | | diff --git a/src/core/public/doc_links/doc_links_service.ts b/src/core/public/doc_links/doc_links_service.ts index 95ac8bba570496..fae7a272c96359 100644 --- a/src/core/public/doc_links/doc_links_service.ts +++ b/src/core/public/doc_links/doc_links_service.ts @@ -38,6 +38,9 @@ export class DocLinksService { links: { dashboard: { drilldowns: `${ELASTIC_WEBSITE_URL}guide/en/kibana/${DOC_LINK_VERSION}/drilldowns.html`, + drilldownsTriggerPicker: `${ELASTIC_WEBSITE_URL}guide/en/kibana/${DOC_LINK_VERSION}/url-drilldown.html#trigger-picker`, + urlDrilldownTemplateSyntax: `${ELASTIC_WEBSITE_URL}guide/en/kibana/${DOC_LINK_VERSION}/url-drilldown.html#templating`, + urlDrilldownVariables: `${ELASTIC_WEBSITE_URL}guide/en/kibana/${DOC_LINK_VERSION}/url-drilldown.html#variables`, }, filebeat: { base: `${ELASTIC_WEBSITE_URL}guide/en/beats/filebeat/${DOC_LINK_VERSION}`, @@ -143,6 +146,9 @@ export interface DocLinksStart { readonly links: { readonly dashboard: { readonly drilldowns: string; + readonly drilldownsTriggerPicker: string; + readonly urlDrilldownTemplateSyntax: string; + readonly urlDrilldownVariables: string; }; readonly filebeat: { readonly base: string; diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index c473ea67d9bcdc..d90b8f780b6744 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -490,6 +490,9 @@ export interface DocLinksStart { readonly links: { readonly dashboard: { readonly drilldowns: string; + readonly drilldownsTriggerPicker: string; + readonly urlDrilldownTemplateSyntax: string; + readonly urlDrilldownVariables: string; }; readonly filebeat: { readonly base: string; diff --git a/x-pack/plugins/embeddable_enhanced/public/drilldowns/url_drilldown/url_drilldown.test.ts b/x-pack/plugins/embeddable_enhanced/public/drilldowns/url_drilldown/url_drilldown.test.ts index 6a11663ea6c3dd..4906d0342be848 100644 --- a/x-pack/plugins/embeddable_enhanced/public/drilldowns/url_drilldown/url_drilldown.test.ts +++ b/x-pack/plugins/embeddable_enhanced/public/drilldowns/url_drilldown/url_drilldown.test.ts @@ -54,6 +54,7 @@ describe('UrlDrilldown', () => { getGlobalScope: () => ({ kibanaUrl: 'http://localhost:5601/' }), getOpenModal: () => Promise.resolve(coreMock.createStart().overlays.openModal), getSyntaxHelpDocsLink: () => 'http://localhost:5601/docs', + getVariablesHelpDocsLink: () => 'http://localhost:5601/docs', navigateToUrl: mockNavigateToUrl, }); diff --git a/x-pack/plugins/embeddable_enhanced/public/drilldowns/url_drilldown/url_drilldown.tsx b/x-pack/plugins/embeddable_enhanced/public/drilldowns/url_drilldown/url_drilldown.tsx index d5ab095fdd2875..80478e6490b8fa 100644 --- a/x-pack/plugins/embeddable_enhanced/public/drilldowns/url_drilldown/url_drilldown.tsx +++ b/x-pack/plugins/embeddable_enhanced/public/drilldowns/url_drilldown/url_drilldown.tsx @@ -31,6 +31,7 @@ interface UrlDrilldownDeps { navigateToUrl: (url: string) => Promise; getOpenModal: () => Promise; getSyntaxHelpDocsLink: () => string; + getVariablesHelpDocsLink: () => string; } export type ActionContext = ChartActionContext; @@ -74,6 +75,7 @@ export class UrlDrilldown implements Drilldown ); }; diff --git a/x-pack/plugins/embeddable_enhanced/public/plugin.ts b/x-pack/plugins/embeddable_enhanced/public/plugin.ts index 37e102b40131d6..187db998e06eaa 100644 --- a/x-pack/plugins/embeddable_enhanced/public/plugin.ts +++ b/x-pack/plugins/embeddable_enhanced/public/plugin.ts @@ -75,7 +75,10 @@ export class EmbeddableEnhancedPlugin navigateToUrl: (url: string) => core.getStartServices().then(([{ application }]) => application.navigateToUrl(url)), getOpenModal: () => core.getStartServices().then(([{ overlays }]) => overlays.openModal), - getSyntaxHelpDocsLink: () => startServices().core.docLinks.links.dashboard.drilldowns, // TODO: replace with docs https://github.com/elastic/kibana/issues/69414 + getSyntaxHelpDocsLink: () => + startServices().core.docLinks.links.dashboard.urlDrilldownTemplateSyntax, + getVariablesHelpDocsLink: () => + startServices().core.docLinks.links.dashboard.urlDrilldownVariables, }) ); diff --git a/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx b/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx index 8154ec45b8ae1b..6f9eccde8bdb07 100644 --- a/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx +++ b/x-pack/plugins/ui_actions_enhanced/public/drilldowns/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx @@ -64,6 +64,7 @@ export function createFlyoutManageDrilldowns({ storage, toastService, docsLink, + triggerPickerDocsLink, getTrigger, }: { actionFactories: ActionFactory[]; @@ -71,6 +72,7 @@ export function createFlyoutManageDrilldowns({ storage: IStorageWrapper; toastService: ToastsStart; docsLink?: string; + triggerPickerDocsLink?: string; }) { const allActionFactoriesById = allActionFactories.reduce((acc, next) => { acc[next.id] = next; @@ -161,6 +163,7 @@ export function createFlyoutManageDrilldowns({ return ( ; + /** + * General overview of drilldowns + */ docsLink?: string; + /** + * Link that explains different triggers + */ + triggerPickerDocsLink?: string; + getTrigger: (triggerId: TriggerId) => Trigger; /** @@ -145,6 +153,7 @@ export function FlyoutDrilldownWizard) { @@ -217,7 +226,7 @@ export function FlyoutDrilldownWizard {mode === 'edit' && ( <> diff --git a/x-pack/plugins/ui_actions_enhanced/public/drilldowns/url_drilldown/components/url_drilldown_collect_config/url_drilldown_collect_config.tsx b/x-pack/plugins/ui_actions_enhanced/public/drilldowns/url_drilldown/components/url_drilldown_collect_config/url_drilldown_collect_config.tsx index dabf09e4b6e9f7..bd0191443d7855 100644 --- a/x-pack/plugins/ui_actions_enhanced/public/drilldowns/url_drilldown/components/url_drilldown_collect_config/url_drilldown_collect_config.tsx +++ b/x-pack/plugins/ui_actions_enhanced/public/drilldowns/url_drilldown/components/url_drilldown_collect_config/url_drilldown_collect_config.tsx @@ -41,6 +41,7 @@ export interface UrlDrilldownCollectConfig { onConfig: (newConfig: UrlDrilldownConfig) => void; scope: UrlDrilldownScope; syntaxHelpDocsLink?: string; + variablesHelpDocsLink?: string; } export const UrlDrilldownCollectConfig: React.FC = ({ @@ -48,6 +49,7 @@ export const UrlDrilldownCollectConfig: React.FC = ({ onConfig, scope, syntaxHelpDocsLink, + variablesHelpDocsLink, }) => { const textAreaRef = useRef(null); const urlTemplate = config.url.template ?? ''; @@ -95,7 +97,7 @@ export const UrlDrilldownCollectConfig: React.FC = ({ labelAppend={ { if (textAreaRef.current) { updateUrlTemplate( diff --git a/x-pack/plugins/ui_actions_enhanced/public/plugin.ts b/x-pack/plugins/ui_actions_enhanced/public/plugin.ts index 015531aab97437..b38bc44abe2b06 100644 --- a/x-pack/plugins/ui_actions_enhanced/public/plugin.ts +++ b/x-pack/plugins/ui_actions_enhanced/public/plugin.ts @@ -132,6 +132,7 @@ export class AdvancedUiActionsPublicPlugin storage: new Storage(window?.localStorage), toastService: core.notifications.toasts, docsLink: core.docLinks.links.dashboard.drilldowns, + triggerPickerDocsLink: core.docLinks.links.dashboard.drilldownsTriggerPicker, }), }; } From 0fd503edc61dcdc1ea95d1941cb198fa63c64e03 Mon Sep 17 00:00:00 2001 From: Anton Dosov Date: Mon, 14 Sep 2020 13:01:20 +0200 Subject: [PATCH 6/6] [UiActions][Drilldowns] Fix actions sorting in context menu (#77162) Co-authored-by: Elastic Machine --- .../public/actions/apply_filter_action.ts | 1 + .../public/lib/actions/apply_filter_action.ts | 1 + .../build_eui_context_menu_panels.test.ts | 81 +++++++++++++++++++ .../build_eui_context_menu_panels.tsx | 12 ++- 4 files changed, 93 insertions(+), 2 deletions(-) create mode 100644 src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.test.ts diff --git a/src/plugins/data/public/actions/apply_filter_action.ts b/src/plugins/data/public/actions/apply_filter_action.ts index a2621e6ce8802f..944da72bd11d1d 100644 --- a/src/plugins/data/public/actions/apply_filter_action.ts +++ b/src/plugins/data/public/actions/apply_filter_action.ts @@ -44,6 +44,7 @@ export function createFilterAction( return createAction({ type: ACTION_GLOBAL_APPLY_FILTER, id: ACTION_GLOBAL_APPLY_FILTER, + order: 100, getIconType: () => 'filter', getDisplayName: () => { return i18n.translate('data.filter.applyFilterActionTitle', { diff --git a/src/plugins/embeddable/public/lib/actions/apply_filter_action.ts b/src/plugins/embeddable/public/lib/actions/apply_filter_action.ts index 1cdb5af00e7483..3460203aac29c6 100644 --- a/src/plugins/embeddable/public/lib/actions/apply_filter_action.ts +++ b/src/plugins/embeddable/public/lib/actions/apply_filter_action.ts @@ -42,6 +42,7 @@ export function createFilterAction(): ActionByType { return createAction({ type: ACTION_APPLY_FILTER, id: ACTION_APPLY_FILTER, + order: 100, getIconType: () => 'filter', getDisplayName: () => { return i18n.translate('embeddableApi.actions.applyFilterActionTitle', { diff --git a/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.test.ts b/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.test.ts new file mode 100644 index 00000000000000..a513bb3c95f24e --- /dev/null +++ b/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.test.ts @@ -0,0 +1,81 @@ +/* + * 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 { buildContextMenuForActions } from './build_eui_context_menu_panels'; +import { Action, createAction } from '../actions'; + +const createTestAction = ({ + type, + dispayName, + order, +}: { + type: string; + dispayName: string; + order: number; +}) => + createAction({ + type: type as any, // mapping doesn't matter for this test + getDisplayName: () => dispayName, + order, + execute: async () => {}, + }); + +test('contextMenu actions sorting: order, type, displayName', async () => { + const actions: Action[] = [ + createTestAction({ + order: 100, + type: '1', + dispayName: 'a', + }), + createTestAction({ + order: 100, + type: '1', + dispayName: 'b', + }), + createTestAction({ + order: 0, + type: '2', + dispayName: 'c', + }), + createTestAction({ + order: 0, + type: '2', + dispayName: 'd', + }), + createTestAction({ + order: 0, + type: '3', + dispayName: 'aa', + }), + ].sort(() => 0.5 - Math.random()); + + const result = await buildContextMenuForActions({ + actions: actions.map((action) => ({ action, context: {}, trigger: '' as any })), + }); + + expect(result.items?.map((item) => item.name as string)).toMatchInlineSnapshot(` + Array [ + "a", + "b", + "c", + "d", + "aa", + ] + `); +}); diff --git a/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx b/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx index b44a07273f4a92..3be1ec781cef6f 100644 --- a/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx +++ b/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx @@ -20,6 +20,7 @@ import * as React from 'react'; import { EuiContextMenuPanelDescriptor, EuiContextMenuPanelItemDescriptor } from '@elastic/eui'; import _ from 'lodash'; +import sortBy from 'lodash/sortBy'; import { i18n } from '@kbn/i18n'; import { uiToReactComponent } from '../../../kibana_react/public'; import { Action } from '../actions'; @@ -46,11 +47,11 @@ interface ActionWithContext { export async function buildContextMenuForActions({ actions, title = defaultTitle, - closeMenu, + closeMenu = () => {}, }: { actions: ActionWithContext[]; title?: string; - closeMenu: () => void; + closeMenu?: () => void; }): Promise { const menuItems = await buildEuiContextMenuPanelItems({ actions, @@ -74,6 +75,13 @@ async function buildEuiContextMenuPanelItems({ actions: ActionWithContext[]; closeMenu: () => void; }) { + actions = sortBy( + actions, + (a) => -1 * (a.action.order ?? 0), + (a) => a.action.type, + (a) => a.action.getDisplayName({ ...a.context, trigger: a.trigger }) + ); + const items: EuiContextMenuPanelItemDescriptor[] = new Array(actions.length); const promises = actions.map(async ({ action, context, trigger }, index) => { const isCompatible = await action.isCompatible({