diff --git a/.ci/build_docker.sh b/.ci/build_docker.sh new file mode 100755 index 0000000000000..1f45182aad840 --- /dev/null +++ b/.ci/build_docker.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +set -euo pipefail + +cd "$(dirname "${0}")" + +cp /usr/local/bin/runbld ./ +cp /usr/local/bin/bash_standard_lib.sh ./ + +docker build -t kibana-ci -f ./Dockerfile . diff --git a/.ci/packer_cache_for_branch.sh b/.ci/packer_cache_for_branch.sh index b8b5f7d3c3f0e..0d9b22b04dbd0 100755 --- a/.ci/packer_cache_for_branch.sh +++ b/.ci/packer_cache_for_branch.sh @@ -53,6 +53,8 @@ tar -cf "$HOME/.kibana/bootstrap_cache/$branch.tar" \ echo "created $HOME/.kibana/bootstrap_cache/$branch.tar" +.ci/build_docker.sh + if [[ "$branch" != "master" ]]; then rm --preserve-root -rf "$checkoutDir" fi diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index af010089e4892..d92725b233e3e 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -9,6 +9,7 @@ /x-pack/plugins/discover_enhanced/ @elastic/kibana-app /x-pack/plugins/lens/ @elastic/kibana-app /x-pack/plugins/graph/ @elastic/kibana-app +/x-pack/plugins/vis_type_timeseries_enhanced/ @elastic/kibana-app /src/plugins/advanced_settings/ @elastic/kibana-app /src/plugins/charts/ @elastic/kibana-app /src/plugins/discover/ @elastic/kibana-app diff --git a/Jenkinsfile b/Jenkinsfile index e33bf67f28df5..3b68cde206573 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,6 +1,5 @@ #!/bin/groovy -env.KBN_ES_SNAPSHOT_USE_UNVERIFIED = 'true' library 'kibana-pipeline-library' kibanaLibrary.load() diff --git a/docs/developer/plugin-list.asciidoc b/docs/developer/plugin-list.asciidoc index e89b6d86361c7..198b0372d9254 100644 --- a/docs/developer/plugin-list.asciidoc +++ b/docs/developer/plugin-list.asciidoc @@ -479,6 +479,10 @@ Elastic. |Welcome to the Kibana rollup plugin! This plugin provides Kibana support for Elasticsearch's rollup feature. Please refer to the Elasticsearch documentation to understand rollup indices and how to create rollup jobs. +|{kib-repo}blob/{branch}/x-pack/plugins/runtime_fields/README.md[runtimeFields] +|Welcome to the home of the runtime field editor and everything related to runtime fields! + + |{kib-repo}blob/{branch}/x-pack/plugins/saved_objects_tagging/README.md[savedObjectsTagging] |Add tagging capability to saved objects @@ -554,6 +558,10 @@ in their infrastructure. |NOTE: This plugin contains implementation of URL drilldown. For drilldowns infrastructure code refer to ui_actions_enhanced plugin. +|{kib-repo}blob/{branch}/x-pack/plugins/vis_type_timeseries_enhanced/README.md[visTypeTimeseriesEnhanced] +|The vis_type_timeseries_enhanced plugin is the x-pack counterpart to the OSS vis_type_timeseries plugin. + + |{kib-repo}blob/{branch}/x-pack/plugins/watcher/README.md[watcher] |This plugins adopts some conventions in addition to or in place of conventions in Kibana (at the time of the plugin's creation): diff --git a/docs/development/core/public/kibana-plugin-core-public.md b/docs/development/core/public/kibana-plugin-core-public.md index b8b1bdcdee3be..6a90fd49f1d66 100644 --- a/docs/development/core/public/kibana-plugin-core-public.md +++ b/docs/development/core/public/kibana-plugin-core-public.md @@ -82,6 +82,11 @@ The plugin integrates with the core system via lifecycle events: `setup` | [NotificationsSetup](./kibana-plugin-core-public.notificationssetup.md) | | | [NotificationsStart](./kibana-plugin-core-public.notificationsstart.md) | | | [OverlayBannersStart](./kibana-plugin-core-public.overlaybannersstart.md) | | +| [OverlayFlyoutOpenOptions](./kibana-plugin-core-public.overlayflyoutopenoptions.md) | | +| [OverlayFlyoutStart](./kibana-plugin-core-public.overlayflyoutstart.md) | APIs to open and manage fly-out dialogs. | +| [OverlayModalConfirmOptions](./kibana-plugin-core-public.overlaymodalconfirmoptions.md) | | +| [OverlayModalOpenOptions](./kibana-plugin-core-public.overlaymodalopenoptions.md) | | +| [OverlayModalStart](./kibana-plugin-core-public.overlaymodalstart.md) | APIs to open and manage modal dialogs. | | [OverlayRef](./kibana-plugin-core-public.overlayref.md) | Returned by [OverlayStart](./kibana-plugin-core-public.overlaystart.md) methods for closing a mounted overlay. | | [OverlayStart](./kibana-plugin-core-public.overlaystart.md) | | | [Plugin](./kibana-plugin-core-public.plugin.md) | The interface that should be returned by a PluginInitializer. | diff --git a/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions._data-test-subj_.md b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions._data-test-subj_.md new file mode 100644 index 0000000000000..d583aae0e0b19 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions._data-test-subj_.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayFlyoutOpenOptions](./kibana-plugin-core-public.overlayflyoutopenoptions.md) > ["data-test-subj"](./kibana-plugin-core-public.overlayflyoutopenoptions._data-test-subj_.md) + +## OverlayFlyoutOpenOptions."data-test-subj" property + +Signature: + +```typescript +'data-test-subj'?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.classname.md b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.classname.md new file mode 100644 index 0000000000000..26f6db77cccea --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.classname.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayFlyoutOpenOptions](./kibana-plugin-core-public.overlayflyoutopenoptions.md) > [className](./kibana-plugin-core-public.overlayflyoutopenoptions.classname.md) + +## OverlayFlyoutOpenOptions.className property + +Signature: + +```typescript +className?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.closebuttonarialabel.md b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.closebuttonarialabel.md new file mode 100644 index 0000000000000..44014b7f0d816 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.closebuttonarialabel.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayFlyoutOpenOptions](./kibana-plugin-core-public.overlayflyoutopenoptions.md) > [closeButtonAriaLabel](./kibana-plugin-core-public.overlayflyoutopenoptions.closebuttonarialabel.md) + +## OverlayFlyoutOpenOptions.closeButtonAriaLabel property + +Signature: + +```typescript +closeButtonAriaLabel?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.md b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.md new file mode 100644 index 0000000000000..5945bca01f55f --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayFlyoutOpenOptions](./kibana-plugin-core-public.overlayflyoutopenoptions.md) + +## OverlayFlyoutOpenOptions interface + + +Signature: + +```typescript +export interface OverlayFlyoutOpenOptions +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| ["data-test-subj"](./kibana-plugin-core-public.overlayflyoutopenoptions._data-test-subj_.md) | string | | +| [className](./kibana-plugin-core-public.overlayflyoutopenoptions.classname.md) | string | | +| [closeButtonAriaLabel](./kibana-plugin-core-public.overlayflyoutopenoptions.closebuttonarialabel.md) | string | | +| [ownFocus](./kibana-plugin-core-public.overlayflyoutopenoptions.ownfocus.md) | boolean | | + diff --git a/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.ownfocus.md b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.ownfocus.md new file mode 100644 index 0000000000000..337ce2c48e1d9 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutopenoptions.ownfocus.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayFlyoutOpenOptions](./kibana-plugin-core-public.overlayflyoutopenoptions.md) > [ownFocus](./kibana-plugin-core-public.overlayflyoutopenoptions.ownfocus.md) + +## OverlayFlyoutOpenOptions.ownFocus property + +Signature: + +```typescript +ownFocus?: boolean; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlayflyoutstart.md b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutstart.md new file mode 100644 index 0000000000000..790fd57320413 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutstart.md @@ -0,0 +1,20 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayFlyoutStart](./kibana-plugin-core-public.overlayflyoutstart.md) + +## OverlayFlyoutStart interface + +APIs to open and manage fly-out dialogs. + +Signature: + +```typescript +export interface OverlayFlyoutStart +``` + +## Methods + +| Method | Description | +| --- | --- | +| [open(mount, options)](./kibana-plugin-core-public.overlayflyoutstart.open.md) | Opens a flyout panel with the given mount point inside. You can use close() on the returned FlyoutRef to close the flyout. | + diff --git a/docs/development/core/public/kibana-plugin-core-public.overlayflyoutstart.open.md b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutstart.open.md new file mode 100644 index 0000000000000..1f740410ca282 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlayflyoutstart.open.md @@ -0,0 +1,25 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayFlyoutStart](./kibana-plugin-core-public.overlayflyoutstart.md) > [open](./kibana-plugin-core-public.overlayflyoutstart.open.md) + +## OverlayFlyoutStart.open() method + +Opens a flyout panel with the given mount point inside. You can use `close()` on the returned FlyoutRef to close the flyout. + +Signature: + +```typescript +open(mount: MountPoint, options?: OverlayFlyoutOpenOptions): OverlayRef; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| mount | MountPoint | | +| options | OverlayFlyoutOpenOptions | | + +Returns: + +`OverlayRef` + diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions._data-test-subj_.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions._data-test-subj_.md new file mode 100644 index 0000000000000..3569b2153c3da --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions._data-test-subj_.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalConfirmOptions](./kibana-plugin-core-public.overlaymodalconfirmoptions.md) > ["data-test-subj"](./kibana-plugin-core-public.overlaymodalconfirmoptions._data-test-subj_.md) + +## OverlayModalConfirmOptions."data-test-subj" property + +Signature: + +```typescript +'data-test-subj'?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.buttoncolor.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.buttoncolor.md new file mode 100644 index 0000000000000..5c827e19e42e1 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.buttoncolor.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalConfirmOptions](./kibana-plugin-core-public.overlaymodalconfirmoptions.md) > [buttonColor](./kibana-plugin-core-public.overlaymodalconfirmoptions.buttoncolor.md) + +## OverlayModalConfirmOptions.buttonColor property + +Signature: + +```typescript +buttonColor?: EuiConfirmModalProps['buttonColor']; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.cancelbuttontext.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.cancelbuttontext.md new file mode 100644 index 0000000000000..0c0b9fd48dbd6 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.cancelbuttontext.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalConfirmOptions](./kibana-plugin-core-public.overlaymodalconfirmoptions.md) > [cancelButtonText](./kibana-plugin-core-public.overlaymodalconfirmoptions.cancelbuttontext.md) + +## OverlayModalConfirmOptions.cancelButtonText property + +Signature: + +```typescript +cancelButtonText?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.classname.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.classname.md new file mode 100644 index 0000000000000..0a622aeaac418 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.classname.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalConfirmOptions](./kibana-plugin-core-public.overlaymodalconfirmoptions.md) > [className](./kibana-plugin-core-public.overlaymodalconfirmoptions.classname.md) + +## OverlayModalConfirmOptions.className property + +Signature: + +```typescript +className?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.closebuttonarialabel.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.closebuttonarialabel.md new file mode 100644 index 0000000000000..8a321a0b07b4c --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.closebuttonarialabel.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalConfirmOptions](./kibana-plugin-core-public.overlaymodalconfirmoptions.md) > [closeButtonAriaLabel](./kibana-plugin-core-public.overlaymodalconfirmoptions.closebuttonarialabel.md) + +## OverlayModalConfirmOptions.closeButtonAriaLabel property + +Signature: + +```typescript +closeButtonAriaLabel?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.confirmbuttontext.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.confirmbuttontext.md new file mode 100644 index 0000000000000..f84d834369f5b --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.confirmbuttontext.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalConfirmOptions](./kibana-plugin-core-public.overlaymodalconfirmoptions.md) > [confirmButtonText](./kibana-plugin-core-public.overlaymodalconfirmoptions.confirmbuttontext.md) + +## OverlayModalConfirmOptions.confirmButtonText property + +Signature: + +```typescript +confirmButtonText?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.defaultfocusedbutton.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.defaultfocusedbutton.md new file mode 100644 index 0000000000000..c5edf48b54ea8 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.defaultfocusedbutton.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalConfirmOptions](./kibana-plugin-core-public.overlaymodalconfirmoptions.md) > [defaultFocusedButton](./kibana-plugin-core-public.overlaymodalconfirmoptions.defaultfocusedbutton.md) + +## OverlayModalConfirmOptions.defaultFocusedButton property + +Signature: + +```typescript +defaultFocusedButton?: EuiConfirmModalProps['defaultFocusedButton']; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.maxwidth.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.maxwidth.md new file mode 100644 index 0000000000000..488b4eb3794fb --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.maxwidth.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalConfirmOptions](./kibana-plugin-core-public.overlaymodalconfirmoptions.md) > [maxWidth](./kibana-plugin-core-public.overlaymodalconfirmoptions.maxwidth.md) + +## OverlayModalConfirmOptions.maxWidth property + +Sets the max-width of the modal. Set to `true` to use the default (`euiBreakpoints 'm'`), set to `false` to not restrict the width, set to a number for a custom width in px, set to a string for a custom width in custom measurement. + +Signature: + +```typescript +maxWidth?: boolean | number | string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.md new file mode 100644 index 0000000000000..83405a151a372 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.md @@ -0,0 +1,27 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalConfirmOptions](./kibana-plugin-core-public.overlaymodalconfirmoptions.md) + +## OverlayModalConfirmOptions interface + + +Signature: + +```typescript +export interface OverlayModalConfirmOptions +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| ["data-test-subj"](./kibana-plugin-core-public.overlaymodalconfirmoptions._data-test-subj_.md) | string | | +| [buttonColor](./kibana-plugin-core-public.overlaymodalconfirmoptions.buttoncolor.md) | EuiConfirmModalProps['buttonColor'] | | +| [cancelButtonText](./kibana-plugin-core-public.overlaymodalconfirmoptions.cancelbuttontext.md) | string | | +| [className](./kibana-plugin-core-public.overlaymodalconfirmoptions.classname.md) | string | | +| [closeButtonAriaLabel](./kibana-plugin-core-public.overlaymodalconfirmoptions.closebuttonarialabel.md) | string | | +| [confirmButtonText](./kibana-plugin-core-public.overlaymodalconfirmoptions.confirmbuttontext.md) | string | | +| [defaultFocusedButton](./kibana-plugin-core-public.overlaymodalconfirmoptions.defaultfocusedbutton.md) | EuiConfirmModalProps['defaultFocusedButton'] | | +| [maxWidth](./kibana-plugin-core-public.overlaymodalconfirmoptions.maxwidth.md) | boolean | number | string | Sets the max-width of the modal. Set to true to use the default (euiBreakpoints 'm'), set to false to not restrict the width, set to a number for a custom width in px, set to a string for a custom width in custom measurement. | +| [title](./kibana-plugin-core-public.overlaymodalconfirmoptions.title.md) | string | | + diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.title.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.title.md new file mode 100644 index 0000000000000..cfbe41e0a7e9f --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalconfirmoptions.title.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalConfirmOptions](./kibana-plugin-core-public.overlaymodalconfirmoptions.md) > [title](./kibana-plugin-core-public.overlaymodalconfirmoptions.title.md) + +## OverlayModalConfirmOptions.title property + +Signature: + +```typescript +title?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions._data-test-subj_.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions._data-test-subj_.md new file mode 100644 index 0000000000000..f0eba659dc62b --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions._data-test-subj_.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalOpenOptions](./kibana-plugin-core-public.overlaymodalopenoptions.md) > ["data-test-subj"](./kibana-plugin-core-public.overlaymodalopenoptions._data-test-subj_.md) + +## OverlayModalOpenOptions."data-test-subj" property + +Signature: + +```typescript +'data-test-subj'?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions.classname.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions.classname.md new file mode 100644 index 0000000000000..769387b8c35ff --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions.classname.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalOpenOptions](./kibana-plugin-core-public.overlaymodalopenoptions.md) > [className](./kibana-plugin-core-public.overlaymodalopenoptions.classname.md) + +## OverlayModalOpenOptions.className property + +Signature: + +```typescript +className?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions.closebuttonarialabel.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions.closebuttonarialabel.md new file mode 100644 index 0000000000000..4e685055b9e17 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions.closebuttonarialabel.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalOpenOptions](./kibana-plugin-core-public.overlaymodalopenoptions.md) > [closeButtonAriaLabel](./kibana-plugin-core-public.overlaymodalopenoptions.closebuttonarialabel.md) + +## OverlayModalOpenOptions.closeButtonAriaLabel property + +Signature: + +```typescript +closeButtonAriaLabel?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions.md new file mode 100644 index 0000000000000..5c0ef8fb1ec86 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalopenoptions.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalOpenOptions](./kibana-plugin-core-public.overlaymodalopenoptions.md) + +## OverlayModalOpenOptions interface + + +Signature: + +```typescript +export interface OverlayModalOpenOptions +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| ["data-test-subj"](./kibana-plugin-core-public.overlaymodalopenoptions._data-test-subj_.md) | string | | +| [className](./kibana-plugin-core-public.overlaymodalopenoptions.classname.md) | string | | +| [closeButtonAriaLabel](./kibana-plugin-core-public.overlaymodalopenoptions.closebuttonarialabel.md) | string | | + diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalstart.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalstart.md new file mode 100644 index 0000000000000..1d8fe1a92dd90 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalstart.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalStart](./kibana-plugin-core-public.overlaymodalstart.md) + +## OverlayModalStart interface + +APIs to open and manage modal dialogs. + +Signature: + +```typescript +export interface OverlayModalStart +``` + +## Methods + +| Method | Description | +| --- | --- | +| [open(mount, options)](./kibana-plugin-core-public.overlaymodalstart.open.md) | Opens a modal panel with the given mount point inside. You can use close() on the returned OverlayRef to close the modal. | +| [openConfirm(message, options)](./kibana-plugin-core-public.overlaymodalstart.openconfirm.md) | Opens a confirmation modal with the given text or mountpoint as a message. Returns a Promise resolving to true if user confirmed or false otherwise. | + diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalstart.open.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalstart.open.md new file mode 100644 index 0000000000000..1c6b82e37a624 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalstart.open.md @@ -0,0 +1,25 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalStart](./kibana-plugin-core-public.overlaymodalstart.md) > [open](./kibana-plugin-core-public.overlaymodalstart.open.md) + +## OverlayModalStart.open() method + +Opens a modal panel with the given mount point inside. You can use `close()` on the returned OverlayRef to close the modal. + +Signature: + +```typescript +open(mount: MountPoint, options?: OverlayModalOpenOptions): OverlayRef; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| mount | MountPoint | | +| options | OverlayModalOpenOptions | | + +Returns: + +`OverlayRef` + diff --git a/docs/development/core/public/kibana-plugin-core-public.overlaymodalstart.openconfirm.md b/docs/development/core/public/kibana-plugin-core-public.overlaymodalstart.openconfirm.md new file mode 100644 index 0000000000000..b0052c0f6460e --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.overlaymodalstart.openconfirm.md @@ -0,0 +1,25 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [OverlayModalStart](./kibana-plugin-core-public.overlaymodalstart.md) > [openConfirm](./kibana-plugin-core-public.overlaymodalstart.openconfirm.md) + +## OverlayModalStart.openConfirm() method + +Opens a confirmation modal with the given text or mountpoint as a message. Returns a Promise resolving to `true` if user confirmed or `false` otherwise. + +Signature: + +```typescript +openConfirm(message: MountPoint | string, options?: OverlayModalConfirmOptions): Promise; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| message | MountPoint | string | | +| options | OverlayModalConfirmOptions | | + +Returns: + +`Promise` + diff --git a/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.adapters.data.md b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.adapters.data.md new file mode 100644 index 0000000000000..0ddbcb3546d1e --- /dev/null +++ b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.adapters.data.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-embeddable-public](./kibana-plugin-plugins-embeddable-public.md) > [Adapters](./kibana-plugin-plugins-embeddable-public.adapters.md) > [data](./kibana-plugin-plugins-embeddable-public.adapters.data.md) + +## Adapters.data property + +Signature: + +```typescript +data?: DataAdapter; +``` diff --git a/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.adapters.md b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.adapters.md index 9635b36cdf05a..47484dc79d88c 100644 --- a/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.adapters.md +++ b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.adapters.md @@ -11,3 +11,11 @@ The interface that the adapters used to open an inspector have to fullfill. ```typescript export interface Adapters ``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [data](./kibana-plugin-plugins-embeddable-public.adapters.data.md) | DataAdapter | | +| [requests](./kibana-plugin-plugins-embeddable-public.adapters.requests.md) | RequestAdapter | | + diff --git a/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.adapters.requests.md b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.adapters.requests.md new file mode 100644 index 0000000000000..2954ad86138ff --- /dev/null +++ b/docs/development/plugins/embeddable/public/kibana-plugin-plugins-embeddable-public.adapters.requests.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-embeddable-public](./kibana-plugin-plugins-embeddable-public.md) > [Adapters](./kibana-plugin-plugins-embeddable-public.adapters.md) > [requests](./kibana-plugin-plugins-embeddable-public.adapters.requests.md) + +## Adapters.requests property + +Signature: + +```typescript +requests?: RequestAdapter; +``` diff --git a/package.json b/package.json index a2c085c0424b1..2560be4f55d08 100644 --- a/package.json +++ b/package.json @@ -598,7 +598,7 @@ "broadcast-channel": "^3.0.3", "chai": "3.5.0", "chance": "1.0.18", - "chromedriver": "^86.0.0", + "chromedriver": "^87.0.0", "clean-webpack-plugin": "^3.0.0", "cmd-shim": "^2.1.0", "compare-versions": "3.5.1", diff --git a/packages/kbn-optimizer/limits.yml b/packages/kbn-optimizer/limits.yml index e326c8e2cac39..7cdbe844c2901 100644 --- a/packages/kbn-optimizer/limits.yml +++ b/packages/kbn-optimizer/limits.yml @@ -102,4 +102,5 @@ pageLoadAssetSize: visualizations: 295025 visualize: 57431 watcher: 43598 + runtimeFields: 41752 stackAlerts: 29684 diff --git a/src/core/public/index.ts b/src/core/public/index.ts index 1393e69d55e51..564bbd712c535 100644 --- a/src/core/public/index.ts +++ b/src/core/public/index.ts @@ -167,7 +167,16 @@ export { IHttpResponseInterceptorOverrides, } from './http'; -export { OverlayStart, OverlayBannersStart, OverlayRef } from './overlays'; +export { + OverlayStart, + OverlayBannersStart, + OverlayRef, + OverlayFlyoutStart, + OverlayFlyoutOpenOptions, + OverlayModalOpenOptions, + OverlayModalConfirmOptions, + OverlayModalStart, +} from './overlays'; export { Toast, diff --git a/src/core/public/overlays/index.ts b/src/core/public/overlays/index.ts index 417486f78f719..31b524d85abbe 100644 --- a/src/core/public/overlays/index.ts +++ b/src/core/public/overlays/index.ts @@ -20,5 +20,5 @@ export { OverlayRef } from './types'; export { OverlayBannersStart } from './banners'; export { OverlayFlyoutStart, OverlayFlyoutOpenOptions } from './flyout'; -export { OverlayModalStart, OverlayModalOpenOptions } from './modal'; +export { OverlayModalStart, OverlayModalOpenOptions, OverlayModalConfirmOptions } from './modal'; export { OverlayService, OverlayStart } from './overlay_service'; diff --git a/src/core/public/overlays/modal/index.ts b/src/core/public/overlays/modal/index.ts index 9ef4492af3a3a..4e270838eae44 100644 --- a/src/core/public/overlays/modal/index.ts +++ b/src/core/public/overlays/modal/index.ts @@ -17,4 +17,9 @@ * under the License. */ -export { ModalService, OverlayModalStart, OverlayModalOpenOptions } from './modal_service'; +export { + ModalService, + OverlayModalStart, + OverlayModalOpenOptions, + OverlayModalConfirmOptions, +} from './modal_service'; diff --git a/src/core/public/overlays/modal/modal_service.tsx b/src/core/public/overlays/modal/modal_service.tsx index f3bbd5c94bdb4..4c0c205ae5438 100644 --- a/src/core/public/overlays/modal/modal_service.tsx +++ b/src/core/public/overlays/modal/modal_service.tsx @@ -70,6 +70,14 @@ export interface OverlayModalConfirmOptions { 'data-test-subj'?: string; defaultFocusedButton?: EuiConfirmModalProps['defaultFocusedButton']; buttonColor?: EuiConfirmModalProps['buttonColor']; + /** + * Sets the max-width of the modal. + * Set to `true` to use the default (`euiBreakpoints 'm'`), + * set to `false` to not restrict the width, + * set to a number for a custom width in px, + * set to a string for a custom width in custom measurement. + */ + maxWidth?: boolean | number | string; } /** diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index 28a20845426d9..37e57a9ee606e 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -862,6 +862,60 @@ export interface OverlayBannersStart { replace(id: string | undefined, mount: MountPoint, priority?: number): string; } +// @public (undocumented) +export interface OverlayFlyoutOpenOptions { + // (undocumented) + 'data-test-subj'?: string; + // (undocumented) + className?: string; + // (undocumented) + closeButtonAriaLabel?: string; + // (undocumented) + ownFocus?: boolean; +} + +// @public +export interface OverlayFlyoutStart { + open(mount: MountPoint, options?: OverlayFlyoutOpenOptions): OverlayRef; +} + +// @public (undocumented) +export interface OverlayModalConfirmOptions { + // (undocumented) + 'data-test-subj'?: string; + // (undocumented) + buttonColor?: EuiConfirmModalProps['buttonColor']; + // (undocumented) + cancelButtonText?: string; + // (undocumented) + className?: string; + // (undocumented) + closeButtonAriaLabel?: string; + // (undocumented) + confirmButtonText?: string; + // (undocumented) + defaultFocusedButton?: EuiConfirmModalProps['defaultFocusedButton']; + maxWidth?: boolean | number | string; + // (undocumented) + title?: string; +} + +// @public (undocumented) +export interface OverlayModalOpenOptions { + // (undocumented) + 'data-test-subj'?: string; + // (undocumented) + className?: string; + // (undocumented) + closeButtonAriaLabel?: string; +} + +// @public +export interface OverlayModalStart { + open(mount: MountPoint, options?: OverlayModalOpenOptions): OverlayRef; + openConfirm(message: MountPoint | string, options?: OverlayModalConfirmOptions): Promise; +} + // @public export interface OverlayRef { close(): Promise; @@ -874,12 +928,8 @@ export interface OverlayStart { banners: OverlayBannersStart; // (undocumented) openConfirm: OverlayModalStart['openConfirm']; - // Warning: (ae-forgotten-export) The symbol "OverlayFlyoutStart" needs to be exported by the entry point index.d.ts - // // (undocumented) openFlyout: OverlayFlyoutStart['open']; - // Warning: (ae-forgotten-export) The symbol "OverlayModalStart" needs to be exported by the entry point index.d.ts - // // (undocumented) openModal: OverlayModalStart['open']; } diff --git a/src/fixtures/telemetry_collectors/nested_collector.ts b/src/fixtures/telemetry_collectors/nested_collector.ts index bde89fe4a7060..ce563b46b0c4e 100644 --- a/src/fixtures/telemetry_collectors/nested_collector.ts +++ b/src/fixtures/telemetry_collectors/nested_collector.ts @@ -29,7 +29,7 @@ interface Usage { } export class NestedInside { - collector?: UsageCollector; + collector?: UsageCollector; createMyCollector() { this.collector = collectorSet.makeUsageCollector({ type: 'my_nested_collector', diff --git a/src/plugins/data/common/search/aggs/agg_type.ts b/src/plugins/data/common/search/aggs/agg_type.ts index 3ffac0c12eb22..4f4a593764b1e 100644 --- a/src/plugins/data/common/search/aggs/agg_type.ts +++ b/src/plugins/data/common/search/aggs/agg_type.ts @@ -54,7 +54,7 @@ export interface AggTypeConfig< aggConfigs: IAggConfigs, aggConfig: TAggConfig, searchSource: ISearchSource, - inspectorRequestAdapter: RequestAdapter, + inspectorRequestAdapter?: RequestAdapter, abortSignal?: AbortSignal ) => Promise; getSerializedFormat?: (agg: TAggConfig) => SerializedFieldFormat; @@ -189,7 +189,7 @@ export class AggType< aggConfigs: IAggConfigs, aggConfig: TAggConfig, searchSource: ISearchSource, - inspectorRequestAdapter: RequestAdapter, + inspectorRequestAdapter?: RequestAdapter, abortSignal?: AbortSignal ) => Promise; /** diff --git a/src/plugins/data/common/search/aggs/buckets/terms.ts b/src/plugins/data/common/search/aggs/buckets/terms.ts index 3d543e6c5f574..ac65e7fa813b3 100644 --- a/src/plugins/data/common/search/aggs/buckets/terms.ts +++ b/src/plugins/data/common/search/aggs/buckets/terms.ts @@ -19,6 +19,7 @@ import { noop } from 'lodash'; import { i18n } from '@kbn/i18n'; +import type { RequestAdapter } from 'src/plugins/inspector/common'; import { BucketAggType, IBucketAggConfig } from './bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; @@ -111,27 +112,32 @@ export const getTermsBucketAgg = () => nestedSearchSource.setField('aggs', filterAgg); - const request = inspectorRequestAdapter.start( - i18n.translate('data.search.aggs.buckets.terms.otherBucketTitle', { - defaultMessage: 'Other bucket', - }), - { - description: i18n.translate('data.search.aggs.buckets.terms.otherBucketDescription', { - defaultMessage: - 'This request counts the number of documents that fall ' + - 'outside the criterion of the data buckets.', + let request: ReturnType | undefined; + if (inspectorRequestAdapter) { + request = inspectorRequestAdapter.start( + i18n.translate('data.search.aggs.buckets.terms.otherBucketTitle', { + defaultMessage: 'Other bucket', }), - } - ); - nestedSearchSource.getSearchRequestBody().then((body) => { - request.json(body); - }); - request.stats(getRequestInspectorStats(nestedSearchSource)); + { + description: i18n.translate('data.search.aggs.buckets.terms.otherBucketDescription', { + defaultMessage: + 'This request counts the number of documents that fall ' + + 'outside the criterion of the data buckets.', + }), + } + ); + nestedSearchSource.getSearchRequestBody().then((body) => { + request!.json(body); + }); + request.stats(getRequestInspectorStats(nestedSearchSource)); + } const response = await nestedSearchSource.fetch({ abortSignal }); - request - .stats(getResponseInspectorStats(response, nestedSearchSource)) - .ok({ json: response }); + if (request) { + request + .stats(getResponseInspectorStats(response, nestedSearchSource)) + .ok({ json: response }); + } resp = mergeOtherBucketAggResponse(aggConfigs, resp, response, aggConfig, filterAgg()); } if (aggConfig.params.missingBucket) { diff --git a/src/plugins/data/public/autocomplete/autocomplete_service.ts b/src/plugins/data/public/autocomplete/autocomplete_service.ts index 2136a405baad6..5e9aede0760fe 100644 --- a/src/plugins/data/public/autocomplete/autocomplete_service.ts +++ b/src/plugins/data/public/autocomplete/autocomplete_service.ts @@ -18,6 +18,7 @@ */ import { CoreSetup, PluginInitializerContext } from 'src/core/public'; +import { TimefilterSetup } from '../query'; import { QuerySuggestionGetFn } from './providers/query_suggestion_provider'; import { getEmptyValueSuggestions, @@ -57,9 +58,9 @@ export class AutocompleteService { private hasQuerySuggestions = (language: string) => this.querySuggestionProviders.has(language); /** @public **/ - public setup(core: CoreSetup) { + public setup(core: CoreSetup, { timefilter }: { timefilter: TimefilterSetup }) { this.getValueSuggestions = this.autocompleteConfig.valueSuggestions.enabled - ? setupValueSuggestionProvider(core) + ? setupValueSuggestionProvider(core, { timefilter }) : getEmptyValueSuggestions; return { diff --git a/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.test.ts b/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.test.ts index 0ef5b7db958e4..4e1745ffcabb2 100644 --- a/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.test.ts +++ b/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.test.ts @@ -18,29 +18,10 @@ */ import { stubIndexPattern, stubFields } from '../../stubs'; +import { TimefilterSetup } from '../../query'; import { setupValueSuggestionProvider, ValueSuggestionsGetFn } from './value_suggestion_provider'; import { IUiSettingsClient, CoreSetup } from 'kibana/public'; -jest.mock('../../services', () => ({ - getQueryService: () => ({ - timefilter: { - timefilter: { - createFilter: () => { - return { - time: 'fake', - }; - }, - getTime: () => { - return { - to: 'now', - from: 'now-15m', - }; - }, - }, - }, - }), -})); - describe('FieldSuggestions', () => { let getValueSuggestions: ValueSuggestionsGetFn; let http: any; @@ -50,7 +31,23 @@ describe('FieldSuggestions', () => { const uiSettings = { get: (key: string) => shouldSuggestValues } as IUiSettingsClient; http = { fetch: jest.fn() }; - getValueSuggestions = setupValueSuggestionProvider({ http, uiSettings } as CoreSetup); + getValueSuggestions = setupValueSuggestionProvider({ http, uiSettings } as CoreSetup, { + timefilter: ({ + timefilter: { + createFilter: () => { + return { + time: 'fake', + }; + }, + getTime: () => { + return { + to: 'now', + from: 'now-15m', + }; + }, + }, + } as unknown) as TimefilterSetup, + }); }); describe('with value suggestions disabled', () => { diff --git a/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.ts b/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.ts index fe9f939a0261d..ee92fce02dda5 100644 --- a/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.ts +++ b/src/plugins/data/public/autocomplete/providers/value_suggestion_provider.ts @@ -21,7 +21,7 @@ import dateMath from '@elastic/datemath'; import { memoize } from 'lodash'; import { CoreSetup } from 'src/core/public'; import { IIndexPattern, IFieldType, UI_SETTINGS, buildQueryFromFilters } from '../../../common'; -import { getQueryService } from '../../services'; +import { TimefilterSetup } from '../../query'; function resolver(title: string, field: IFieldType, query: string, filters: any[]) { // Only cache results for a minute @@ -40,8 +40,10 @@ interface ValueSuggestionsGetFnArgs { signal?: AbortSignal; } -const getAutocompleteTimefilter = (indexPattern: IIndexPattern) => { - const { timefilter } = getQueryService().timefilter; +const getAutocompleteTimefilter = ( + { timefilter }: TimefilterSetup, + indexPattern: IIndexPattern +) => { const timeRange = timefilter.getTime(); // Use a rounded timerange so that memoizing works properly @@ -54,7 +56,10 @@ const getAutocompleteTimefilter = (indexPattern: IIndexPattern) => { export const getEmptyValueSuggestions = (() => Promise.resolve([])) as ValueSuggestionsGetFn; -export const setupValueSuggestionProvider = (core: CoreSetup): ValueSuggestionsGetFn => { +export const setupValueSuggestionProvider = ( + core: CoreSetup, + { timefilter }: { timefilter: TimefilterSetup } +): ValueSuggestionsGetFn => { const requestSuggestions = memoize( (index: string, field: IFieldType, query: string, filters: any = [], signal?: AbortSignal) => core.http.fetch(`/api/kibana/suggestions/values/${index}`, { @@ -86,7 +91,9 @@ export const setupValueSuggestionProvider = (core: CoreSetup): ValueSuggestionsG return []; } - const timeFilter = useTimeRange ? getAutocompleteTimefilter(indexPattern) : undefined; + const timeFilter = useTimeRange + ? getAutocompleteTimefilter(timefilter, indexPattern) + : undefined; const filterQuery = timeFilter ? buildQueryFromFilters([timeFilter], indexPattern).filter : []; const filters = [...(boolFilter ? boolFilter : []), ...filterQuery]; return await requestSuggestions(title, field, query, filters, signal); diff --git a/src/plugins/data/public/index_patterns/index_pattern.stub.ts b/src/plugins/data/public/index_patterns/index_pattern.stub.ts index e5c6c008e3e28..804f0d7d89225 100644 --- a/src/plugins/data/public/index_patterns/index_pattern.stub.ts +++ b/src/plugins/data/public/index_patterns/index_pattern.stub.ts @@ -20,20 +20,9 @@ import sinon from 'sinon'; import { CoreSetup } from 'src/core/public'; -import { FieldFormat as FieldFormatImpl } from '../../common/field_formats'; import { IFieldType, FieldSpec } from '../../common/index_patterns'; -import { FieldFormatsStart } from '../field_formats'; import { IndexPattern, indexPatterns, KBN_FIELD_TYPES, fieldList } from '../'; import { getFieldFormatsRegistry } from '../test_utils'; -import { setFieldFormats } from '../services'; - -setFieldFormats(({ - getDefaultInstance: () => - ({ - getConverterFor: () => (value: any) => value, - convert: (value: any) => JSON.stringify(value), - } as FieldFormatImpl), -} as unknown) as FieldFormatsStart); export function getStubIndexPattern( pattern: string, diff --git a/src/plugins/data/public/plugin.ts b/src/plugins/data/public/plugin.ts index afa8d935f367b..7e8283476ffc5 100644 --- a/src/plugins/data/public/plugin.ts +++ b/src/plugins/data/public/plugin.ts @@ -41,16 +41,14 @@ import { UiSettingsPublicToCommon, } from './index_patterns'; import { - setFieldFormats, setIndexPatterns, setNotifications, setOverlays, - setQueryService, setSearchService, setUiSettings, } from './services'; import { createSearchBar } from './ui/search_bar/create_search_bar'; -import { esaggs } from './search/expressions'; +import { getEsaggs } from './search/expressions'; import { SELECT_RANGE_TRIGGER, VALUE_CLICK_TRIGGER, @@ -111,8 +109,22 @@ export class DataPublicPlugin ): DataPublicPluginSetup { const startServices = createStartServicesGetter(core.getStartServices); - expressions.registerFunction(esaggs); expressions.registerFunction(indexPatternLoad); + expressions.registerFunction( + getEsaggs({ + getStartDependencies: async () => { + const [, , self] = await core.getStartServices(); + const { fieldFormats, indexPatterns, query, search } = self; + return { + addFilters: query.filterManager.addFilters.bind(query.filterManager), + aggs: search.aggs, + deserializeFieldFormat: fieldFormats.deserialize.bind(fieldFormats), + indexPatterns, + searchSource: search.searchSource, + }; + }, + }) + ); this.usageCollection = usageCollection; @@ -145,7 +157,7 @@ export class DataPublicPlugin }); return { - autocomplete: this.autocomplete.setup(core), + autocomplete: this.autocomplete.setup(core, { timefilter: queryService.timefilter }), search: searchService, fieldFormats: this.fieldFormatsService.setup(core), query: queryService, @@ -162,7 +174,6 @@ export class DataPublicPlugin setUiSettings(uiSettings); const fieldFormats = this.fieldFormatsService.start(); - setFieldFormats(fieldFormats); const indexPatterns = new IndexPatternsService({ uiSettings: new UiSettingsPublicToCommon(uiSettings), @@ -186,7 +197,6 @@ export class DataPublicPlugin savedObjectsClient: savedObjects.client, uiSettings, }); - setQueryService(query); const search = this.searchService.start(core, { fieldFormats, indexPatterns }); setSearchService(search); diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 0768658e40299..165e11517311c 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -27,6 +27,7 @@ import { EuiButtonEmptyProps } from '@elastic/eui'; import { EuiComboBoxProps } from '@elastic/eui'; import { EuiConfirmModalProps } from '@elastic/eui'; import { EuiGlobalToastListToast } from '@elastic/eui'; +import { EventEmitter } from 'events'; import { ExclusiveUnion } from '@elastic/eui'; import { ExecutionContext } from 'src/plugins/expressions/common'; import { ExpressionAstFunction } from 'src/plugins/expressions/common'; @@ -66,7 +67,7 @@ import * as React_2 from 'react'; import { RecursiveReadonly } from '@kbn/utility-types'; import { Reporter } from '@kbn/analytics'; import { RequestAdapter } from 'src/plugins/inspector/common'; -import { RequestStatistics } from 'src/plugins/inspector/common'; +import { RequestStatistics as RequestStatistics_2 } from 'src/plugins/inspector/common'; import { Required } from '@kbn/utility-types'; import * as Rx from 'rxjs'; import { SavedObject } from 'src/core/server'; diff --git a/src/plugins/data/public/search/expressions/esaggs.ts b/src/plugins/data/public/search/expressions/esaggs.ts deleted file mode 100644 index 3932484801fa8..0000000000000 --- a/src/plugins/data/public/search/expressions/esaggs.ts +++ /dev/null @@ -1,323 +0,0 @@ -/* - * 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 { get, hasIn } from 'lodash'; -import { i18n } from '@kbn/i18n'; -import { Datatable, DatatableColumn } from 'src/plugins/expressions/public'; -import { PersistedState } from '../../../../../plugins/visualizations/public'; -import { Adapters } from '../../../../../plugins/inspector/public'; - -import { - calculateBounds, - EsaggsExpressionFunctionDefinition, - Filter, - getTime, - IIndexPattern, - isRangeFilter, - Query, - TimeRange, -} from '../../../common'; -import { - getRequestInspectorStats, - getResponseInspectorStats, - IAggConfigs, - ISearchSource, - tabifyAggResponse, -} from '../../../common/search'; - -import { FilterManager } from '../../query'; -import { - getFieldFormats, - getIndexPatterns, - getQueryService, - getSearchService, -} from '../../services'; -import { buildTabularInspectorData } from './build_tabular_inspector_data'; - -export interface RequestHandlerParams { - searchSource: ISearchSource; - aggs: IAggConfigs; - timeRange?: TimeRange; - timeFields?: string[]; - indexPattern?: IIndexPattern; - query?: Query; - filters?: Filter[]; - filterManager: FilterManager; - uiState?: PersistedState; - partialRows?: boolean; - inspectorAdapters: Adapters; - metricsAtAllLevels?: boolean; - visParams?: any; - abortSignal?: AbortSignal; - searchSessionId?: string; -} - -const name = 'esaggs'; - -const handleCourierRequest = async ({ - searchSource, - aggs, - timeRange, - timeFields, - indexPattern, - query, - filters, - partialRows, - metricsAtAllLevels, - inspectorAdapters, - filterManager, - abortSignal, - searchSessionId, -}: RequestHandlerParams) => { - // Create a new search source that inherits the original search source - // but has the appropriate timeRange applied via a filter. - // This is a temporary solution until we properly pass down all required - // information for the request to the request handler (https://github.com/elastic/kibana/issues/16641). - // Using callParentStartHandlers: true we make sure, that the parent searchSource - // onSearchRequestStart will be called properly even though we use an inherited - // search source. - const timeFilterSearchSource = searchSource.createChild({ callParentStartHandlers: true }); - const requestSearchSource = timeFilterSearchSource.createChild({ callParentStartHandlers: true }); - - aggs.setTimeRange(timeRange as TimeRange); - - // For now we need to mirror the history of the passed search source, since - // the request inspector wouldn't work otherwise. - Object.defineProperty(requestSearchSource, 'history', { - get() { - return searchSource.history; - }, - set(history) { - return (searchSource.history = history); - }, - }); - - requestSearchSource.setField('aggs', function () { - return aggs.toDsl(metricsAtAllLevels); - }); - - requestSearchSource.onRequestStart((paramSearchSource, options) => { - return aggs.onSearchRequestStart(paramSearchSource, options); - }); - - // If timeFields have been specified, use the specified ones, otherwise use primary time field of index - // pattern if it's available. - const defaultTimeField = indexPattern?.getTimeField?.(); - const defaultTimeFields = defaultTimeField ? [defaultTimeField.name] : []; - const allTimeFields = timeFields && timeFields.length > 0 ? timeFields : defaultTimeFields; - - // If a timeRange has been specified and we had at least one timeField available, create range - // filters for that those time fields - if (timeRange && allTimeFields.length > 0) { - timeFilterSearchSource.setField('filter', () => { - return allTimeFields - .map((fieldName) => getTime(indexPattern, timeRange, { fieldName })) - .filter(isRangeFilter); - }); - } - - requestSearchSource.setField('filter', filters); - requestSearchSource.setField('query', query); - - inspectorAdapters.requests.reset(); - const request = inspectorAdapters.requests.start( - i18n.translate('data.functions.esaggs.inspector.dataRequest.title', { - defaultMessage: 'Data', - }), - { - description: i18n.translate('data.functions.esaggs.inspector.dataRequest.description', { - defaultMessage: - 'This request queries Elasticsearch to fetch the data for the visualization.', - }), - searchSessionId, - } - ); - request.stats(getRequestInspectorStats(requestSearchSource)); - - try { - const response = await requestSearchSource.fetch({ - abortSignal, - sessionId: searchSessionId, - }); - - request.stats(getResponseInspectorStats(response, searchSource)).ok({ json: response }); - - (searchSource as any).rawResponse = response; - } catch (e) { - // Log any error during request to the inspector - request.error({ json: e }); - throw e; - } finally { - // Add the request body no matter if things went fine or not - requestSearchSource.getSearchRequestBody().then((req: unknown) => { - request.json(req); - }); - } - - // Note that rawResponse is not deeply cloned here, so downstream applications using courier - // must take care not to mutate it, or it could have unintended side effects, e.g. displaying - // response data incorrectly in the inspector. - let resp = (searchSource as any).rawResponse; - for (const agg of aggs.aggs) { - if (hasIn(agg, 'type.postFlightRequest')) { - resp = await agg.type.postFlightRequest( - resp, - aggs, - agg, - requestSearchSource, - inspectorAdapters.requests, - abortSignal - ); - } - } - - (searchSource as any).finalResponse = resp; - - const parsedTimeRange = timeRange ? calculateBounds(timeRange) : null; - const tabifyParams = { - metricsAtAllLevels, - partialRows, - timeRange: parsedTimeRange - ? { from: parsedTimeRange.min, to: parsedTimeRange.max, timeFields: allTimeFields } - : undefined, - }; - - const response = tabifyAggResponse(aggs, (searchSource as any).finalResponse, tabifyParams); - - (searchSource as any).tabifiedResponse = response; - - inspectorAdapters.data.setTabularLoader( - () => - buildTabularInspectorData((searchSource as any).tabifiedResponse, { - queryFilter: filterManager, - deserializeFieldFormat: getFieldFormats().deserialize, - }), - { returnsFormattedValues: true } - ); - - return response; -}; - -export const esaggs = (): EsaggsExpressionFunctionDefinition => ({ - name, - type: 'datatable', - inputTypes: ['kibana_context', 'null'], - help: i18n.translate('data.functions.esaggs.help', { - defaultMessage: 'Run AggConfig aggregation', - }), - args: { - index: { - types: ['string'], - help: '', - }, - metricsAtAllLevels: { - types: ['boolean'], - default: false, - help: '', - }, - partialRows: { - types: ['boolean'], - default: false, - help: '', - }, - includeFormatHints: { - types: ['boolean'], - default: false, - help: '', - }, - aggConfigs: { - types: ['string'], - default: '""', - help: '', - }, - timeFields: { - types: ['string'], - help: '', - multi: true, - }, - }, - async fn(input, args, { inspectorAdapters, abortSignal, getSearchSessionId }) { - const indexPatterns = getIndexPatterns(); - const { filterManager } = getQueryService(); - const searchService = getSearchService(); - - const aggConfigsState = JSON.parse(args.aggConfigs); - const indexPattern = await indexPatterns.get(args.index); - const aggs = searchService.aggs.createAggConfigs(indexPattern, aggConfigsState); - - // we should move searchSource creation inside courier request handler - const searchSource = await searchService.searchSource.create(); - - searchSource.setField('index', indexPattern); - searchSource.setField('size', 0); - - const resolvedTimeRange = input?.timeRange && calculateBounds(input.timeRange); - - const response = await handleCourierRequest({ - searchSource, - aggs, - indexPattern, - timeRange: get(input, 'timeRange', undefined), - query: get(input, 'query', undefined) as any, - filters: get(input, 'filters', undefined), - timeFields: args.timeFields, - metricsAtAllLevels: args.metricsAtAllLevels, - partialRows: args.partialRows, - inspectorAdapters: inspectorAdapters as Adapters, - filterManager, - abortSignal: (abortSignal as unknown) as AbortSignal, - searchSessionId: getSearchSessionId(), - }); - - const table: Datatable = { - type: 'datatable', - rows: response.rows, - columns: response.columns.map((column) => { - const cleanedColumn: DatatableColumn = { - id: column.id, - name: column.name, - meta: { - type: column.aggConfig.params.field?.type || 'number', - field: column.aggConfig.params.field?.name, - index: indexPattern.title, - params: column.aggConfig.toSerializedFieldFormat(), - source: 'esaggs', - sourceParams: { - indexPatternId: indexPattern.id, - appliedTimeRange: - column.aggConfig.params.field?.name && - input?.timeRange && - args.timeFields && - args.timeFields.includes(column.aggConfig.params.field?.name) - ? { - from: resolvedTimeRange?.min?.toISOString(), - to: resolvedTimeRange?.max?.toISOString(), - } - : undefined, - ...column.aggConfig.serialize(), - }, - }, - }; - return cleanedColumn; - }), - }; - - return table; - }, -}); diff --git a/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts b/src/plugins/data/public/search/expressions/esaggs/build_tabular_inspector_data.ts similarity index 78% rename from src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts rename to src/plugins/data/public/search/expressions/esaggs/build_tabular_inspector_data.ts index 7eff6f25fd828..79dedf4131764 100644 --- a/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts +++ b/src/plugins/data/public/search/expressions/esaggs/build_tabular_inspector_data.ts @@ -18,35 +18,41 @@ */ import { set } from '@elastic/safer-lodash-set'; -import { FormattedData } from '../../../../../plugins/inspector/public'; -import { TabbedTable } from '../../../common'; -import { FormatFactory } from '../../../common/field_formats/utils'; -import { createFilter } from './create_filter'; +import { + FormattedData, + TabularData, + TabularDataValue, +} from '../../../../../../plugins/inspector/common'; +import { Filter, TabbedTable } from '../../../../common'; +import { FormatFactory } from '../../../../common/field_formats/utils'; +import { createFilter } from '../create_filter'; /** - * @deprecated + * Type borrowed from the client-side FilterManager['addFilters']. * - * Do not use this function. - * - * @todo This function is used only by Courier. Courier will - * soon be removed, and this function will be deleted, too. If Courier is not removed, - * move this function inside Courier. - * - * --- + * We need to use a custom type to make this isomorphic since FilterManager + * doesn't exist on the server. * + * @internal + */ +export type AddFilters = (filters: Filter[] | Filter, pinFilterStatus?: boolean) => void; + +/** * This function builds tabular data from the response and attaches it to the * inspector. It will only be called when the data view in the inspector is opened. + * + * @internal */ export async function buildTabularInspectorData( table: TabbedTable, { - queryFilter, + addFilters, deserializeFieldFormat, }: { - queryFilter: { addFilters: (filter: any) => void }; + addFilters?: AddFilters; deserializeFieldFormat: FormatFactory; } -) { +): Promise { const aggConfigs = table.columns.map((column) => column.aggConfig); const rows = table.rows.map((row) => { return table.columns.reduce>((prev, cur, colIndex) => { @@ -74,20 +80,22 @@ export async function buildTabularInspectorData( name: col.name, field: `col-${colIndex}-${col.aggConfig.id}`, filter: + addFilters && isCellContentFilterable && - ((value: { raw: unknown }) => { + ((value: TabularDataValue) => { const rowIndex = rows.findIndex( (row) => row[`col-${colIndex}-${col.aggConfig.id}`].raw === value.raw ); const filter = createFilter(aggConfigs, table, colIndex, rowIndex, value.raw); if (filter) { - queryFilter.addFilters(filter); + addFilters(filter); } }), filterOut: + addFilters && isCellContentFilterable && - ((value: { raw: unknown }) => { + ((value: TabularDataValue) => { const rowIndex = rows.findIndex( (row) => row[`col-${colIndex}-${col.aggConfig.id}`].raw === value.raw ); @@ -101,7 +109,7 @@ export async function buildTabularInspectorData( } else { set(filter, 'meta.negate', notOther && notMissing); } - queryFilter.addFilters(filter); + addFilters(filter); } }), }; diff --git a/src/plugins/data/public/search/expressions/esaggs/esaggs_fn.ts b/src/plugins/data/public/search/expressions/esaggs/esaggs_fn.ts new file mode 100644 index 0000000000000..ce3bd9bdaee76 --- /dev/null +++ b/src/plugins/data/public/search/expressions/esaggs/esaggs_fn.ts @@ -0,0 +1,155 @@ +/* + * 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 { get } from 'lodash'; +import { i18n } from '@kbn/i18n'; + +import { Datatable, DatatableColumn } from 'src/plugins/expressions/common'; +import { Adapters } from 'src/plugins/inspector/common'; + +import { calculateBounds, EsaggsExpressionFunctionDefinition } from '../../../../common'; +import { FormatFactory } from '../../../../common/field_formats/utils'; +import { IndexPatternsContract } from '../../../../common/index_patterns/index_patterns'; +import { ISearchStartSearchSource, AggsStart } from '../../../../common/search'; + +import { AddFilters } from './build_tabular_inspector_data'; +import { handleRequest } from './request_handler'; + +const name = 'esaggs'; + +interface StartDependencies { + addFilters: AddFilters; + aggs: AggsStart; + deserializeFieldFormat: FormatFactory; + indexPatterns: IndexPatternsContract; + searchSource: ISearchStartSearchSource; +} + +export function getEsaggs({ + getStartDependencies, +}: { + getStartDependencies: () => Promise; +}) { + return (): EsaggsExpressionFunctionDefinition => ({ + name, + type: 'datatable', + inputTypes: ['kibana_context', 'null'], + help: i18n.translate('data.functions.esaggs.help', { + defaultMessage: 'Run AggConfig aggregation', + }), + args: { + index: { + types: ['string'], + help: '', + }, + metricsAtAllLevels: { + types: ['boolean'], + default: false, + help: '', + }, + partialRows: { + types: ['boolean'], + default: false, + help: '', + }, + includeFormatHints: { + types: ['boolean'], + default: false, + help: '', + }, + aggConfigs: { + types: ['string'], + default: '""', + help: '', + }, + timeFields: { + types: ['string'], + help: '', + multi: true, + }, + }, + async fn(input, args, { inspectorAdapters, abortSignal, getSearchSessionId }) { + const { + addFilters, + aggs, + deserializeFieldFormat, + indexPatterns, + searchSource, + } = await getStartDependencies(); + + const aggConfigsState = JSON.parse(args.aggConfigs); + const indexPattern = await indexPatterns.get(args.index); + const aggConfigs = aggs.createAggConfigs(indexPattern, aggConfigsState); + + const resolvedTimeRange = input?.timeRange && calculateBounds(input.timeRange); + + const response = await handleRequest({ + abortSignal: (abortSignal as unknown) as AbortSignal, + addFilters, + aggs: aggConfigs, + deserializeFieldFormat, + filters: get(input, 'filters', undefined), + indexPattern, + inspectorAdapters: inspectorAdapters as Adapters, + metricsAtAllLevels: args.metricsAtAllLevels, + partialRows: args.partialRows, + query: get(input, 'query', undefined) as any, + searchSessionId: getSearchSessionId(), + searchSourceService: searchSource, + timeFields: args.timeFields, + timeRange: get(input, 'timeRange', undefined), + }); + + const table: Datatable = { + type: 'datatable', + rows: response.rows, + columns: response.columns.map((column) => { + const cleanedColumn: DatatableColumn = { + id: column.id, + name: column.name, + meta: { + type: column.aggConfig.params.field?.type || 'number', + field: column.aggConfig.params.field?.name, + index: indexPattern.title, + params: column.aggConfig.toSerializedFieldFormat(), + source: name, + sourceParams: { + indexPatternId: indexPattern.id, + appliedTimeRange: + column.aggConfig.params.field?.name && + input?.timeRange && + args.timeFields && + args.timeFields.includes(column.aggConfig.params.field?.name) + ? { + from: resolvedTimeRange?.min?.toISOString(), + to: resolvedTimeRange?.max?.toISOString(), + } + : undefined, + ...column.aggConfig.serialize(), + }, + }, + }; + return cleanedColumn; + }), + }; + + return table; + }, + }); +} diff --git a/src/plugins/data/public/search/expressions/esaggs/index.ts b/src/plugins/data/public/search/expressions/esaggs/index.ts new file mode 100644 index 0000000000000..cbd3fb9cc5e91 --- /dev/null +++ b/src/plugins/data/public/search/expressions/esaggs/index.ts @@ -0,0 +1,20 @@ +/* + * 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 * from './esaggs_fn'; diff --git a/src/plugins/data/public/search/expressions/esaggs/request_handler.ts b/src/plugins/data/public/search/expressions/esaggs/request_handler.ts new file mode 100644 index 0000000000000..93b5705b821c0 --- /dev/null +++ b/src/plugins/data/public/search/expressions/esaggs/request_handler.ts @@ -0,0 +1,213 @@ +/* + * 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 { i18n } from '@kbn/i18n'; +import { Adapters } from 'src/plugins/inspector/common'; + +import { + calculateBounds, + Filter, + getTime, + IndexPattern, + isRangeFilter, + Query, + TimeRange, +} from '../../../../common'; +import { + getRequestInspectorStats, + getResponseInspectorStats, + IAggConfigs, + ISearchStartSearchSource, + tabifyAggResponse, +} from '../../../../common/search'; +import { FormatFactory } from '../../../../common/field_formats/utils'; + +import { AddFilters, buildTabularInspectorData } from './build_tabular_inspector_data'; + +interface RequestHandlerParams { + abortSignal?: AbortSignal; + addFilters?: AddFilters; + aggs: IAggConfigs; + deserializeFieldFormat: FormatFactory; + filters?: Filter[]; + indexPattern?: IndexPattern; + inspectorAdapters: Adapters; + metricsAtAllLevels?: boolean; + partialRows?: boolean; + query?: Query; + searchSessionId?: string; + searchSourceService: ISearchStartSearchSource; + timeFields?: string[]; + timeRange?: TimeRange; +} + +export const handleRequest = async ({ + abortSignal, + addFilters, + aggs, + deserializeFieldFormat, + filters, + indexPattern, + inspectorAdapters, + metricsAtAllLevels, + partialRows, + query, + searchSessionId, + searchSourceService, + timeFields, + timeRange, +}: RequestHandlerParams) => { + const searchSource = await searchSourceService.create(); + + searchSource.setField('index', indexPattern); + searchSource.setField('size', 0); + + // Create a new search source that inherits the original search source + // but has the appropriate timeRange applied via a filter. + // This is a temporary solution until we properly pass down all required + // information for the request to the request handler (https://github.com/elastic/kibana/issues/16641). + // Using callParentStartHandlers: true we make sure, that the parent searchSource + // onSearchRequestStart will be called properly even though we use an inherited + // search source. + const timeFilterSearchSource = searchSource.createChild({ callParentStartHandlers: true }); + const requestSearchSource = timeFilterSearchSource.createChild({ callParentStartHandlers: true }); + + aggs.setTimeRange(timeRange as TimeRange); + + // For now we need to mirror the history of the passed search source, since + // the request inspector wouldn't work otherwise. + Object.defineProperty(requestSearchSource, 'history', { + get() { + return searchSource.history; + }, + set(history) { + return (searchSource.history = history); + }, + }); + + requestSearchSource.setField('aggs', function () { + return aggs.toDsl(metricsAtAllLevels); + }); + + requestSearchSource.onRequestStart((paramSearchSource, options) => { + return aggs.onSearchRequestStart(paramSearchSource, options); + }); + + // If timeFields have been specified, use the specified ones, otherwise use primary time field of index + // pattern if it's available. + const defaultTimeField = indexPattern?.getTimeField?.(); + const defaultTimeFields = defaultTimeField ? [defaultTimeField.name] : []; + const allTimeFields = timeFields && timeFields.length > 0 ? timeFields : defaultTimeFields; + + // If a timeRange has been specified and we had at least one timeField available, create range + // filters for that those time fields + if (timeRange && allTimeFields.length > 0) { + timeFilterSearchSource.setField('filter', () => { + return allTimeFields + .map((fieldName) => getTime(indexPattern, timeRange, { fieldName })) + .filter(isRangeFilter); + }); + } + + requestSearchSource.setField('filter', filters); + requestSearchSource.setField('query', query); + + let request; + if (inspectorAdapters.requests) { + inspectorAdapters.requests.reset(); + request = inspectorAdapters.requests.start( + i18n.translate('data.functions.esaggs.inspector.dataRequest.title', { + defaultMessage: 'Data', + }), + { + description: i18n.translate('data.functions.esaggs.inspector.dataRequest.description', { + defaultMessage: + 'This request queries Elasticsearch to fetch the data for the visualization.', + }), + searchSessionId, + } + ); + request.stats(getRequestInspectorStats(requestSearchSource)); + } + + try { + const response = await requestSearchSource.fetch({ + abortSignal, + sessionId: searchSessionId, + }); + + if (request) { + request.stats(getResponseInspectorStats(response, searchSource)).ok({ json: response }); + } + + (searchSource as any).rawResponse = response; + } catch (e) { + // Log any error during request to the inspector + if (request) { + request.error({ json: e }); + } + throw e; + } finally { + // Add the request body no matter if things went fine or not + if (request) { + request.json(await requestSearchSource.getSearchRequestBody()); + } + } + + // Note that rawResponse is not deeply cloned here, so downstream applications using courier + // must take care not to mutate it, or it could have unintended side effects, e.g. displaying + // response data incorrectly in the inspector. + let response = (searchSource as any).rawResponse; + for (const agg of aggs.aggs) { + if (typeof agg.type.postFlightRequest === 'function') { + response = await agg.type.postFlightRequest( + response, + aggs, + agg, + requestSearchSource, + inspectorAdapters.requests, + abortSignal + ); + } + } + + const parsedTimeRange = timeRange ? calculateBounds(timeRange) : null; + const tabifyParams = { + metricsAtAllLevels, + partialRows, + timeRange: parsedTimeRange + ? { from: parsedTimeRange.min, to: parsedTimeRange.max, timeFields: allTimeFields } + : undefined, + }; + + const tabifiedResponse = tabifyAggResponse(aggs, response, tabifyParams); + + if (inspectorAdapters.data) { + inspectorAdapters.data.setTabularLoader( + () => + buildTabularInspectorData(tabifiedResponse, { + addFilters, + deserializeFieldFormat, + }), + { returnsFormattedValues: true } + ); + } + + return tabifiedResponse; +}; diff --git a/src/plugins/data/public/services.ts b/src/plugins/data/public/services.ts index 032bce6d8d2aa..28fb4ff8b53ae 100644 --- a/src/plugins/data/public/services.ts +++ b/src/plugins/data/public/services.ts @@ -18,7 +18,6 @@ */ import { NotificationsStart, CoreStart } from 'src/core/public'; -import { FieldFormatsStart } from './field_formats'; import { createGetterSetter } from '../../kibana_utils/public'; import { IndexPatternsContract } from './index_patterns'; import { DataPublicPluginStart } from './types'; @@ -31,20 +30,12 @@ export const [getUiSettings, setUiSettings] = createGetterSetter( - 'FieldFormats' -); - export const [getOverlays, setOverlays] = createGetterSetter('Overlays'); export const [getIndexPatterns, setIndexPatterns] = createGetterSetter( 'IndexPatterns' ); -export const [getQueryService, setQueryService] = createGetterSetter< - DataPublicPluginStart['query'] ->('Query'); - export const [getSearchService, setSearchService] = createGetterSetter< DataPublicPluginStart['search'] >('Search'); diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index b2db4f5c74729..ce66610edf880 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -27,15 +27,15 @@ import { ExpressionAstFunction } from 'src/plugins/expressions/common'; import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common'; import { ExpressionsServerSetup } from 'src/plugins/expressions/server'; import { ExpressionValueBoxed } from 'src/plugins/expressions/common'; -import { ISavedObjectsRepository } from 'kibana/server'; +import { ISavedObjectsRepository } from 'src/core/server'; import { IScopedClusterClient } from 'src/core/server'; import { ISearchOptions as ISearchOptions_2 } from 'src/plugins/data/public'; import { ISearchSource } from 'src/plugins/data/public'; import { IUiSettingsClient } from 'src/core/server'; import { KibanaRequest } from 'src/core/server'; -import { LegacyAPICaller } from 'kibana/server'; -import { Logger } from 'kibana/server'; -import { Logger as Logger_2 } from 'src/core/server'; +import { LegacyAPICaller } from 'src/core/server'; +import { Logger } from 'src/core/server'; +import { Logger as Logger_2 } from 'kibana/server'; import { LoggerFactory } from '@kbn/logging'; import { Moment } from 'moment'; import moment from 'moment'; diff --git a/src/plugins/discover/public/application/embeddable/search_embeddable.ts b/src/plugins/discover/public/application/embeddable/search_embeddable.ts index 170078076ec6f..980e90d0acf20 100644 --- a/src/plugins/discover/public/application/embeddable/search_embeddable.ts +++ b/src/plugins/discover/public/application/embeddable/search_embeddable.ts @@ -84,7 +84,7 @@ export class SearchEmbeddable private readonly savedSearch: SavedSearch; private $rootScope: ng.IRootScopeService; private $compile: ng.ICompileService; - private inspectorAdaptors: Adapters; + private inspectorAdapters: Adapters; private searchScope?: SearchScope; private panelTitle: string = ''; private filtersSearchSource?: ISearchSource; @@ -131,7 +131,7 @@ export class SearchEmbeddable this.savedSearch = savedSearch; this.$rootScope = $rootScope; this.$compile = $compile; - this.inspectorAdaptors = { + this.inspectorAdapters = { requests: new RequestAdapter(), }; this.initializeSearchScope(); @@ -150,7 +150,7 @@ export class SearchEmbeddable } public getInspectorAdapters() { - return this.inspectorAdaptors; + return this.inspectorAdapters; } public getSavedSearch() { @@ -195,7 +195,7 @@ export class SearchEmbeddable const searchScope: SearchScope = (this.searchScope = this.$rootScope.$new()); searchScope.description = this.savedSearch.description; - searchScope.inspectorAdapters = this.inspectorAdaptors; + searchScope.inspectorAdapters = this.inspectorAdapters; const { searchSource } = this.savedSearch; const indexPattern = (searchScope.indexPattern = searchSource.getField('index'))!; @@ -287,7 +287,7 @@ export class SearchEmbeddable ); // Log request to inspector - this.inspectorAdaptors.requests.reset(); + this.inspectorAdapters.requests!.reset(); const title = i18n.translate('discover.embeddable.inspectorRequestDataTitle', { defaultMessage: 'Data', }); @@ -295,7 +295,7 @@ export class SearchEmbeddable defaultMessage: 'This request queries Elasticsearch to fetch the data for the search.', }); - const inspectorRequest = this.inspectorAdaptors.requests.start(title, { + const inspectorRequest = this.inspectorAdapters.requests!.start(title, { description, searchSessionId, }); diff --git a/src/plugins/embeddable/public/public.api.md b/src/plugins/embeddable/public/public.api.md index 6a2565edf2f67..1bdfbe9d01a2f 100644 --- a/src/plugins/embeddable/public/public.api.md +++ b/src/plugins/embeddable/public/public.api.md @@ -28,6 +28,7 @@ import { EuiComboBoxProps } from '@elastic/eui'; import { EuiConfirmModalProps } from '@elastic/eui'; import { EuiContextMenuPanelDescriptor } from '@elastic/eui'; import { EuiGlobalToastListToast } from '@elastic/eui'; +import { EventEmitter } from 'events'; import { ExclusiveUnion } from '@elastic/eui'; import { ExpressionAstFunction } from 'src/plugins/expressions/common'; import { History } from 'history'; @@ -59,7 +60,7 @@ import { PublicMethodsOf } from '@kbn/utility-types'; import { PublicUiSettingsParams } from 'src/core/server/types'; import React from 'react'; import { RecursiveReadonly } from '@kbn/utility-types'; -import { RequestAdapter } from 'src/plugins/inspector/common'; +import { RequestAdapter as RequestAdapter_2 } from 'src/plugins/inspector/common'; import { Required } from '@kbn/utility-types'; import * as Rx from 'rxjs'; import { SavedObject as SavedObject_2 } from 'src/core/server'; @@ -100,6 +101,14 @@ export const ACTION_EDIT_PANEL = "editPanel"; export interface Adapters { // (undocumented) [key: string]: any; + // Warning: (ae-forgotten-export) The symbol "DataAdapter" needs to be exported by the entry point index.d.ts + // + // (undocumented) + data?: DataAdapter; + // Warning: (ae-forgotten-export) The symbol "RequestAdapter" needs to be exported by the entry point index.d.ts + // + // (undocumented) + requests?: RequestAdapter; } // Warning: (ae-forgotten-export) The symbol "ActionContext" needs to be exported by the entry point index.d.ts diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx index a3a0984d4a736..4024eea008588 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx @@ -31,7 +31,7 @@ export interface Props { componentProps?: Record; readDefaultValueOnForm?: boolean; onChange?: (value: I) => void; - children?: (field: FieldHook) => JSX.Element; + children?: (field: FieldHook) => JSX.Element | null; [key: string]: any; } diff --git a/src/plugins/inspector/common/adapters/data/data_adapter.ts b/src/plugins/inspector/common/adapters/data/data_adapter.ts index 34e6c278c693f..a21aa7db39145 100644 --- a/src/plugins/inspector/common/adapters/data/data_adapter.ts +++ b/src/plugins/inspector/common/adapters/data/data_adapter.ts @@ -20,7 +20,7 @@ import { EventEmitter } from 'events'; import { TabularCallback, TabularHolder, TabularLoaderOptions } from './types'; -class DataAdapter extends EventEmitter { +export class DataAdapter extends EventEmitter { private tabular?: TabularCallback; private tabularOptions?: TabularLoaderOptions; @@ -38,5 +38,3 @@ class DataAdapter extends EventEmitter { return Promise.resolve(this.tabular()).then((data) => ({ data, options })); } } - -export { DataAdapter }; diff --git a/src/plugins/inspector/common/adapters/data/data_adapters.test.ts b/src/plugins/inspector/common/adapters/data/data_adapters.test.ts index 287024ca1b59e..7cc52807548f0 100644 --- a/src/plugins/inspector/common/adapters/data/data_adapters.test.ts +++ b/src/plugins/inspector/common/adapters/data/data_adapters.test.ts @@ -35,33 +35,37 @@ describe('DataAdapter', () => { }); it('should call the provided callback and resolve with its value', async () => { - const spy = jest.fn(() => 'foo'); + const data = { columns: [], rows: [] }; + const spy = jest.fn(() => data); adapter.setTabularLoader(spy); expect(spy).not.toBeCalled(); const result = await adapter.getTabular(); expect(spy).toBeCalled(); - expect(result.data).toBe('foo'); + expect(result.data).toBe(data); }); it('should pass through options specified via setTabularLoader', async () => { - adapter.setTabularLoader(() => 'foo', { returnsFormattedValues: true }); + const data = { columns: [], rows: [] }; + adapter.setTabularLoader(() => data, { returnsFormattedValues: true }); const result = await adapter.getTabular(); expect(result.options).toEqual({ returnsFormattedValues: true }); }); it('should return options set when starting loading data', async () => { - adapter.setTabularLoader(() => 'foo', { returnsFormattedValues: true }); + const data = { columns: [], rows: [] }; + adapter.setTabularLoader(() => data, { returnsFormattedValues: true }); const waitForResult = adapter.getTabular(); - adapter.setTabularLoader(() => 'bar', { returnsFormattedValues: false }); + adapter.setTabularLoader(() => data, { returnsFormattedValues: false }); const result = await waitForResult; expect(result.options).toEqual({ returnsFormattedValues: true }); }); }); it('should emit a "tabular" event when a new tabular loader is specified', () => { + const data = { columns: [], rows: [] }; const spy = jest.fn(); adapter.once('change', spy); - adapter.setTabularLoader(() => 42); + adapter.setTabularLoader(() => data); expect(spy).toBeCalled(); }); }); diff --git a/src/plugins/inspector/common/adapters/data/formatted_data.ts b/src/plugins/inspector/common/adapters/data/formatted_data.ts index c752e8670aca3..08c956f27d011 100644 --- a/src/plugins/inspector/common/adapters/data/formatted_data.ts +++ b/src/plugins/inspector/common/adapters/data/formatted_data.ts @@ -17,8 +17,6 @@ * under the License. */ -class FormattedData { +export class FormattedData { constructor(public readonly raw: any, public readonly formatted: any) {} } - -export { FormattedData }; diff --git a/src/plugins/inspector/common/adapters/data/index.ts b/src/plugins/inspector/common/adapters/data/index.ts index 920e298ab455f..a8b1abcd8cd7e 100644 --- a/src/plugins/inspector/common/adapters/data/index.ts +++ b/src/plugins/inspector/common/adapters/data/index.ts @@ -17,5 +17,6 @@ * under the License. */ -export { FormattedData } from './formatted_data'; -export { DataAdapter } from './data_adapter'; +export * from './data_adapter'; +export * from './formatted_data'; +export * from './types'; diff --git a/src/plugins/inspector/common/adapters/data/types.ts b/src/plugins/inspector/common/adapters/data/types.ts index 1c7b17c143eca..040724f4ae36e 100644 --- a/src/plugins/inspector/common/adapters/data/types.ts +++ b/src/plugins/inspector/common/adapters/data/types.ts @@ -17,8 +17,25 @@ * under the License. */ -// TODO: add a more specific TabularData type. -export type TabularData = any; +export interface TabularDataValue { + formatted: string; + raw: unknown; +} + +export interface TabularDataColumn { + name: string; + field: string; + filter?: (value: TabularDataValue) => void; + filterOut?: (value: TabularDataValue) => void; +} + +export type TabularDataRow = Record; + +export interface TabularData { + columns: TabularDataColumn[]; + rows: TabularDataRow[]; +} + export type TabularCallback = () => TabularData | Promise; export interface TabularHolder { diff --git a/src/plugins/inspector/common/adapters/index.ts b/src/plugins/inspector/common/adapters/index.ts index 1e7a44a2c60b1..0c6319a2905a8 100644 --- a/src/plugins/inspector/common/adapters/index.ts +++ b/src/plugins/inspector/common/adapters/index.ts @@ -17,12 +17,6 @@ * under the License. */ -export { Adapters } from './types'; -export { DataAdapter, FormattedData } from './data'; -export { - RequestAdapter, - RequestStatistic, - RequestStatistics, - RequestStatus, - RequestResponder, -} from './request'; +export * from './data'; +export * from './request'; +export * from './types'; diff --git a/src/plugins/inspector/common/adapters/request/request_adapter.ts b/src/plugins/inspector/common/adapters/request/request_adapter.ts index af10d1b77b16d..5f5728e1cf331 100644 --- a/src/plugins/inspector/common/adapters/request/request_adapter.ts +++ b/src/plugins/inspector/common/adapters/request/request_adapter.ts @@ -29,7 +29,7 @@ import { Request, RequestParams, RequestStatus } from './types'; * instead it offers a generic API to log requests of any kind. * @extends EventEmitter */ -class RequestAdapter extends EventEmitter { +export class RequestAdapter extends EventEmitter { private requests: Map; constructor() { @@ -78,5 +78,3 @@ class RequestAdapter extends EventEmitter { this.emit('change'); } } - -export { RequestAdapter }; diff --git a/src/plugins/inspector/common/adapters/types.ts b/src/plugins/inspector/common/adapters/types.ts index 362c69e299c9d..b51c3e56c749f 100644 --- a/src/plugins/inspector/common/adapters/types.ts +++ b/src/plugins/inspector/common/adapters/types.ts @@ -17,9 +17,14 @@ * under the License. */ +import type { DataAdapter } from './data'; +import type { RequestAdapter } from './request'; + /** * The interface that the adapters used to open an inspector have to fullfill. */ export interface Adapters { + data?: DataAdapter; + requests?: RequestAdapter; [key: string]: any; } diff --git a/src/plugins/inspector/common/index.ts b/src/plugins/inspector/common/index.ts index 06ab36a577d98..c5755b22095dc 100644 --- a/src/plugins/inspector/common/index.ts +++ b/src/plugins/inspector/common/index.ts @@ -17,4 +17,17 @@ * under the License. */ -export * from './adapters'; +export { + Adapters, + DataAdapter, + FormattedData, + RequestAdapter, + RequestStatistic, + RequestStatistics, + RequestStatus, + RequestResponder, + TabularData, + TabularDataColumn, + TabularDataRow, + TabularDataValue, +} from './adapters'; diff --git a/src/plugins/inspector/public/test/is_available.test.ts b/src/plugins/inspector/public/test/is_available.test.ts index 0604129a0734a..c38d9d7a3f825 100644 --- a/src/plugins/inspector/public/test/is_available.test.ts +++ b/src/plugins/inspector/public/test/is_available.test.ts @@ -18,8 +18,7 @@ */ import { inspectorPluginMock } from '../mocks'; -import { DataAdapter } from '../../common/adapters/data/data_adapter'; -import { RequestAdapter } from '../../common/adapters/request/request_adapter'; +import { DataAdapter, RequestAdapter } from '../../common/adapters'; const adapter1 = new DataAdapter(); const adapter2 = new RequestAdapter(); diff --git a/src/plugins/inspector/public/views/data/components/data_view.tsx b/src/plugins/inspector/public/views/data/components/data_view.tsx index 100fa7787321c..324094d8f93d0 100644 --- a/src/plugins/inspector/public/views/data/components/data_view.tsx +++ b/src/plugins/inspector/public/views/data/components/data_view.tsx @@ -35,7 +35,7 @@ import { Adapters } from '../../../../common'; import { TabularLoaderOptions, TabularData, - TabularCallback, + TabularHolder, } from '../../../../common/adapters/data/types'; import { IUiSettingsClient } from '../../../../../../core/public'; import { withKibana, KibanaReactContextValue } from '../../../../../kibana_react/public'; @@ -44,7 +44,7 @@ interface DataViewComponentState { tabularData: TabularData | null; tabularOptions: TabularLoaderOptions; adapters: Adapters; - tabularPromise: TabularCallback | null; + tabularPromise: Promise | null; } interface DataViewComponentProps extends InspectorViewProps { @@ -73,7 +73,7 @@ class DataViewComponent extends Component string; + export interface DataViewColumn { name: string; field: string; - sortable: (item: DataViewRow) => string | number; + sortable: (item: TabularDataRow) => string | number; render: DataViewColumnRender; } -type DataViewColumnRender = (value: string, _item: DataViewRow) => string; - -export interface DataViewRow { - [fields: string]: { - formatted: string; - raw: any; - }; -} +export type DataViewRow = TabularDataRow; diff --git a/src/plugins/inspector/public/views/requests/components/requests_view.tsx b/src/plugins/inspector/public/views/requests/components/requests_view.tsx index 7762689daf4e6..e1879f7a6b6c8 100644 --- a/src/plugins/inspector/public/views/requests/components/requests_view.tsx +++ b/src/plugins/inspector/public/views/requests/components/requests_view.tsx @@ -31,7 +31,7 @@ import { RequestDetails } from './request_details'; interface RequestSelectorState { requests: Request[]; - request: Request; + request: Request | null; } export class RequestsViewComponent extends Component { @@ -43,9 +43,9 @@ export class RequestsViewComponent extends Component { - const requests = this.props.adapters.requests.getRequests(); + const requests = this.props.adapters.requests!.getRequests(); const newState = { requests } as RequestSelectorState; - if (!requests.includes(this.state.request)) { + if (!this.state.request || !requests.includes(this.state.request)) { newState.request = requests.length ? requests[0] : null; } this.setState(newState); @@ -69,7 +69,7 @@ export class RequestsViewComponent extends Component - - + {this.state.request && ( + <> + + + + )} {this.state.request && this.state.request.description && ( diff --git a/src/plugins/kibana_usage_collection/server/collectors/application_usage/telemetry_application_usage_collector.test.ts b/src/plugins/kibana_usage_collection/server/collectors/application_usage/telemetry_application_usage_collector.test.ts index c1457c64080a6..6cb104416ef58 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/application_usage/telemetry_application_usage_collector.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/application_usage/telemetry_application_usage_collector.test.ts @@ -19,7 +19,7 @@ import { savedObjectsRepositoryMock, loggingSystemMock } from '../../../../../core/server/mocks'; import { - CollectorOptions, + Collector, createUsageCollectionSetupMock, } from '../../../../usage_collection/server/usage_collection.mock'; @@ -40,11 +40,11 @@ describe('telemetry_application_usage', () => { const logger = loggingSystemMock.createLogger(); - let collector: CollectorOptions; + let collector: Collector; const usageCollectionMock = createUsageCollectionSetupMock(); usageCollectionMock.makeUsageCollector.mockImplementation((config) => { - collector = config; + collector = new Collector(logger, config); return createUsageCollectionSetupMock().makeUsageCollector(config); }); diff --git a/src/plugins/kibana_usage_collection/server/collectors/core/index.test.ts b/src/plugins/kibana_usage_collection/server/collectors/core/index.test.ts index e8efa9997c459..e31437a744e29 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/core/index.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/core/index.test.ts @@ -18,20 +18,22 @@ */ import { - CollectorOptions, + Collector, createUsageCollectionSetupMock, } from '../../../../usage_collection/server/usage_collection.mock'; import { createCollectorFetchContextMock } from 'src/plugins/usage_collection/server/mocks'; import { registerCoreUsageCollector } from '.'; -import { coreUsageDataServiceMock } from '../../../../../core/server/mocks'; +import { coreUsageDataServiceMock, loggingSystemMock } from '../../../../../core/server/mocks'; import { CoreUsageData } from 'src/core/server/'; +const logger = loggingSystemMock.createLogger(); + describe('telemetry_core', () => { - let collector: CollectorOptions; + let collector: Collector; const usageCollectionMock = createUsageCollectionSetupMock(); usageCollectionMock.makeUsageCollector.mockImplementation((config) => { - collector = config; + collector = new Collector(logger, config); return createUsageCollectionSetupMock().makeUsageCollector(config); }); diff --git a/src/plugins/kibana_usage_collection/server/collectors/csp/csp_collector.test.ts b/src/plugins/kibana_usage_collection/server/collectors/csp/csp_collector.test.ts index 03184d7385861..2851382f7559a 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/csp/csp_collector.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/csp/csp_collector.test.ts @@ -19,8 +19,13 @@ import { CspConfig, ICspConfig } from '../../../../../core/server'; import { createCspCollector } from './csp_collector'; -import { httpServiceMock } from '../../../../../core/server/mocks'; -import { createCollectorFetchContextMock } from 'src/plugins/usage_collection/server/mocks'; +import { httpServiceMock, loggingSystemMock } from '../../../../../core/server/mocks'; +import { + Collector, + createCollectorFetchContextMock, +} from 'src/plugins/usage_collection/server/mocks'; + +const logger = loggingSystemMock.createLogger(); describe('csp collector', () => { let httpMock: ReturnType; @@ -36,7 +41,7 @@ describe('csp collector', () => { }); test('fetches whether strict mode is enabled', async () => { - const collector = createCspCollector(httpMock); + const collector = new Collector(logger, createCspCollector(httpMock)); expect((await collector.fetch(mockedFetchContext)).strict).toEqual(true); @@ -45,7 +50,7 @@ describe('csp collector', () => { }); test('fetches whether the legacy browser warning is enabled', async () => { - const collector = createCspCollector(httpMock); + const collector = new Collector(logger, createCspCollector(httpMock)); expect((await collector.fetch(mockedFetchContext)).warnLegacyBrowsers).toEqual(true); @@ -54,7 +59,7 @@ describe('csp collector', () => { }); test('fetches whether the csp rules have been changed or not', async () => { - const collector = createCspCollector(httpMock); + const collector = new Collector(logger, createCspCollector(httpMock)); expect((await collector.fetch(mockedFetchContext)).rulesChangedFromDefault).toEqual(false); @@ -63,7 +68,7 @@ describe('csp collector', () => { }); test('does not include raw csp rules under any property names', async () => { - const collector = createCspCollector(httpMock); + const collector = new Collector(logger, createCspCollector(httpMock)); // It's important that we do not send the value of csp.rules here as it // can be customized with values that can be identifiable to given diff --git a/src/plugins/kibana_usage_collection/server/collectors/kibana/index.test.ts b/src/plugins/kibana_usage_collection/server/collectors/kibana/index.test.ts index 88ccb2016d420..16a60eca60f47 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/kibana/index.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/kibana/index.test.ts @@ -17,20 +17,25 @@ * under the License. */ -import { pluginInitializerContextConfigMock } from '../../../../../core/server/mocks'; import { - CollectorOptions, + loggingSystemMock, + pluginInitializerContextConfigMock, +} from '../../../../../core/server/mocks'; +import { + Collector, createUsageCollectionSetupMock, } from '../../../../usage_collection/server/usage_collection.mock'; import { createCollectorFetchContextMock } from '../../../../usage_collection/server/mocks'; import { registerKibanaUsageCollector } from './'; +const logger = loggingSystemMock.createLogger(); + describe('telemetry_kibana', () => { - let collector: CollectorOptions; + let collector: Collector; const usageCollectionMock = createUsageCollectionSetupMock(); usageCollectionMock.makeUsageCollector.mockImplementation((config) => { - collector = config; + collector = new Collector(logger, config); return createUsageCollectionSetupMock().makeUsageCollector(config); }); diff --git a/src/plugins/kibana_usage_collection/server/collectors/management/index.test.ts b/src/plugins/kibana_usage_collection/server/collectors/management/index.test.ts index e671f739ee083..0aafee01cf49d 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/management/index.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/management/index.test.ts @@ -17,21 +17,23 @@ * under the License. */ -import { uiSettingsServiceMock } from '../../../../../core/server/mocks'; +import { loggingSystemMock, uiSettingsServiceMock } from '../../../../../core/server/mocks'; import { - CollectorOptions, + Collector, createUsageCollectionSetupMock, createCollectorFetchContextMock, } from '../../../../usage_collection/server/usage_collection.mock'; import { registerManagementUsageCollector } from './'; +const logger = loggingSystemMock.createLogger(); + describe('telemetry_application_usage_collector', () => { - let collector: CollectorOptions; + let collector: Collector; const usageCollectionMock = createUsageCollectionSetupMock(); usageCollectionMock.makeUsageCollector.mockImplementation((config) => { - collector = config; + collector = new Collector(logger, config); return createUsageCollectionSetupMock().makeUsageCollector(config); }); diff --git a/src/plugins/kibana_usage_collection/server/collectors/ops_stats/index.test.ts b/src/plugins/kibana_usage_collection/server/collectors/ops_stats/index.test.ts index 61990730812cc..8db7010e64026 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/ops_stats/index.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/ops_stats/index.test.ts @@ -19,20 +19,23 @@ import { Subject } from 'rxjs'; import { - CollectorOptions, + Collector, createUsageCollectionSetupMock, createCollectorFetchContextMock, } from '../../../../usage_collection/server/usage_collection.mock'; import { registerOpsStatsCollector } from './'; import { OpsMetrics } from '../../../../../core/server'; +import { loggingSystemMock } from '../../../../../core/server/mocks'; + +const logger = loggingSystemMock.createLogger(); describe('telemetry_ops_stats', () => { - let collector: CollectorOptions; + let collector: Collector; const usageCollectionMock = createUsageCollectionSetupMock(); usageCollectionMock.makeStatsCollector.mockImplementation((config) => { - collector = config; + collector = new Collector(logger, config); return createUsageCollectionSetupMock().makeStatsCollector(config); }); diff --git a/src/plugins/kibana_usage_collection/server/collectors/ui_metric/index.test.ts b/src/plugins/kibana_usage_collection/server/collectors/ui_metric/index.test.ts index 48e4e0d99d3cd..90e3b7110e1dc 100644 --- a/src/plugins/kibana_usage_collection/server/collectors/ui_metric/index.test.ts +++ b/src/plugins/kibana_usage_collection/server/collectors/ui_metric/index.test.ts @@ -17,21 +17,23 @@ * under the License. */ -import { savedObjectsRepositoryMock } from '../../../../../core/server/mocks'; +import { loggingSystemMock, savedObjectsRepositoryMock } from '../../../../../core/server/mocks'; import { - CollectorOptions, + Collector, createUsageCollectionSetupMock, createCollectorFetchContextMock, } from '../../../../usage_collection/server/usage_collection.mock'; import { registerUiMetricUsageCollector } from './'; +const logger = loggingSystemMock.createLogger(); + describe('telemetry_ui_metric', () => { - let collector: CollectorOptions; + let collector: Collector; const usageCollectionMock = createUsageCollectionSetupMock(); usageCollectionMock.makeUsageCollector.mockImplementation((config) => { - collector = config; + collector = new Collector(logger, config); return createUsageCollectionSetupMock().makeUsageCollector(config); }); diff --git a/src/plugins/telemetry/server/telemetry_collection/get_kibana.ts b/src/plugins/telemetry/server/telemetry_collection/get_kibana.ts index 654c5435650cf..207a467ca5fd0 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_kibana.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_kibana.ts @@ -21,6 +21,7 @@ import { omit } from 'lodash'; import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; import { ISavedObjectsRepository, + KibanaRequest, LegacyAPICaller, SavedObjectsClientContract, } from 'kibana/server'; @@ -89,8 +90,14 @@ export async function getKibana( usageCollection: UsageCollectionSetup, callWithInternalUser: LegacyAPICaller, asInternalUser: ElasticsearchClient, - soClient: SavedObjectsClientContract | ISavedObjectsRepository + soClient: SavedObjectsClientContract | ISavedObjectsRepository, + kibanaRequest: KibanaRequest | undefined // intentionally `| undefined` to enforce providing the parameter ): Promise { - const usage = await usageCollection.bulkFetch(callWithInternalUser, asInternalUser, soClient); + const usage = await usageCollection.bulkFetch( + callWithInternalUser, + asInternalUser, + soClient, + kibanaRequest + ); return usageCollection.toObject(usage); } diff --git a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts index 9298b36ac3ea6..6231fd29e7d3d 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts @@ -24,7 +24,7 @@ import { usageCollectionPluginMock, createCollectorFetchContextMock, } from '../../../usage_collection/server/mocks'; -import { elasticsearchServiceMock } from '../../../../../src/core/server/mocks'; +import { elasticsearchServiceMock, httpServerMock } from '../../../../../src/core/server/mocks'; function mockUsageCollection(kibanaUsage = {}) { const usageCollection = usageCollectionPluginMock.createSetupContract(); @@ -87,6 +87,7 @@ function mockStatsCollectionConfig(clusterInfo: any, clusterStats: any, kibana: ...createCollectorFetchContextMock(), esClient: mockGetLocalStats(clusterInfo, clusterStats), usageCollection: mockUsageCollection(kibana), + kibanaRequest: httpServerMock.createKibanaRequest(), timestamp: Date.now(), }; } diff --git a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts index 4aeefb1d81d6a..a3666683a05a1 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts @@ -62,16 +62,16 @@ export type TelemetryLocalStats = ReturnType; /** * Get statistics for all products joined by Elasticsearch cluster. - * @param {Array} cluster uuids - * @param {Object} config contains the new esClient already scoped contains usageCollection, callCluster, esClient, start, end + * @param {Array} cluster uuids array of cluster uuid's + * @param {Object} config contains the usageCollection, callCluster (deprecated), the esClient and Saved Objects client scoped to the request or the internal repository, and the kibana request * @param {Object} StatsCollectionContext contains logger and version (string) */ export const getLocalStats: StatsGetter<{}, TelemetryLocalStats> = async ( - clustersDetails, // array of cluster uuid's - config, // contains the new esClient already scoped contains usageCollection, callCluster, esClient, start, end and the saved objects client scoped to the request or the internal repository - context // StatsCollectionContext contains logger and version (string) + clustersDetails, + config, + context ) => { - const { callCluster, usageCollection, esClient, soClient } = config; + const { callCluster, usageCollection, esClient, soClient, kibanaRequest } = config; return await Promise.all( clustersDetails.map(async (clustersDetail) => { @@ -79,7 +79,7 @@ export const getLocalStats: StatsGetter<{}, TelemetryLocalStats> = async ( getClusterInfo(esClient), // cluster info getClusterStats(esClient), // cluster stats (not to be confused with cluster _state_) getNodesUsage(esClient), // nodes_usage info - getKibana(usageCollection, callCluster, esClient, soClient), + getKibana(usageCollection, callCluster, esClient, soClient, kibanaRequest), getDataTelemetry(esClient), ]); return handleLocalStats( diff --git a/src/plugins/telemetry_collection_manager/server/plugin.ts b/src/plugins/telemetry_collection_manager/server/plugin.ts index e1e1379097adf..2cd06f13a8855 100644 --- a/src/plugins/telemetry_collection_manager/server/plugin.ts +++ b/src/plugins/telemetry_collection_manager/server/plugin.ts @@ -157,7 +157,10 @@ export class TelemetryCollectionManagerPlugin const soClient = config.unencrypted ? collectionSoService.getScopedClient(config.request) : collectionSoService.createInternalRepository(); - return { callCluster, timestamp, usageCollection, esClient, soClient }; + // Provide the kibanaRequest so opted-in plugins can scope their custom clients only if the request is not encrypted + const kibanaRequest = config.unencrypted ? request : void 0; + + return { callCluster, timestamp, usageCollection, esClient, soClient, kibanaRequest }; } private async getOptInStats(optInStatus: boolean, config: StatsGetterConfig) { diff --git a/src/plugins/telemetry_collection_manager/server/types.ts b/src/plugins/telemetry_collection_manager/server/types.ts index 0100fdbbb3970..7d25b8c8261c4 100644 --- a/src/plugins/telemetry_collection_manager/server/types.ts +++ b/src/plugins/telemetry_collection_manager/server/types.ts @@ -79,6 +79,7 @@ export interface StatsCollectionConfig { timestamp: number; esClient: ElasticsearchClient; soClient: SavedObjectsClientContract | ISavedObjectsRepository; + kibanaRequest: KibanaRequest | undefined; // intentionally `| undefined` to enforce providing the parameter } export interface BasicStatsPayload { diff --git a/src/plugins/ui_actions/public/public.api.md b/src/plugins/ui_actions/public/public.api.md index 3e40c94e116fb..3a14f49169e09 100644 --- a/src/plugins/ui_actions/public/public.api.md +++ b/src/plugins/ui_actions/public/public.api.md @@ -8,6 +8,7 @@ import { CoreSetup } from 'src/core/public'; import { CoreStart } from 'src/core/public'; import { EnvironmentMode } from '@kbn/config'; import { EuiContextMenuPanelDescriptor } from '@elastic/eui'; +import { EventEmitter } from 'events'; import { Observable } from 'rxjs'; import { PackageInfo } from '@kbn/config'; import { Plugin } from 'src/core/public'; diff --git a/src/plugins/usage_collection/README.md b/src/plugins/usage_collection/README.md index 2ac3de510f8ae..5e6ed901c7647 100644 --- a/src/plugins/usage_collection/README.md +++ b/src/plugins/usage_collection/README.md @@ -31,7 +31,7 @@ Then you need to make the Telemetry service aware of the collector by registerin ```ts // server/plugin.ts import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; - import { CoreSetup, CoreStart } from 'kibana/server'; + import { CoreSetup, CoreStart } from 'src/core/server'; class Plugin { public setup(core: CoreSetup, plugins: { usageCollection?: UsageCollectionSetup }) { @@ -46,7 +46,7 @@ Then you need to make the Telemetry service aware of the collector by registerin ```ts // server/collectors/register.ts import { UsageCollectionSetup, CollectorFetchContext } from 'src/plugins/usage_collection/server'; - import { APICluster } from 'kibana/server'; + import { APICluster } from 'src/core/server'; interface Usage { my_objects: { @@ -95,8 +95,8 @@ Some background: - `isReady` (added in v7.2.0 and v6.8.4) is a way for a usage collector to announce that some async process must finish first before it can return data in the `fetch` method (e.g. a client needs to ne initialized, or the task manager needs to run a task first). If any collector reports that it is not ready when we call its `fetch` method, we reset a flag to try again and, after a set amount of time, collect data from those collectors that are ready and skip any that are not. This means that if a collector returns `true` for `isReady` and it actually isn't ready to return data, there won't be telemetry data from that collector in that telemetry report (usually once per day). You should consider what it means if your collector doesn't return data in the first few documents when Kibana starts or, if we should wait for any other reason (e.g. the task manager needs to run your task first). If you need to tell telemetry collection to wait, you should implement this function with custom logic. If your `fetch` method can run without the need of any previous dependencies, then you can return true for `isReady` as shown in the example below. -- The `fetch` method needs to support multiple contexts in which it is called. For example, when stats are pulled from a Kibana Metricbeat module, the Beat calls Kibana's stats API to invoke usage collection. -In this case, the `fetch` method is called as a result of an HTTP API request and `callCluster` wraps `callWithRequest` or `esClient` wraps `asCurrentUser`, where the request headers are expected to have read privilege on the entire `.kibana' index. The `fetch` method also exposes the saved objects client that will have the correct scope when the collectors' `fetch` method is called. +- The `fetch` method needs to support multiple contexts in which it is called. For example, when a user requests the example of what we collect in the **Kibana>Advanced Settings>Usage data** section, the clients provided in the context of the function (`CollectorFetchContext`) are scoped to that user's privileges. The reason is to avoid exposing via telemetry any data that user should not have access to (i.e.: if the user does not have access to certain indices, they shouldn't be allowed to see the number of documents that exists in it). In this case, the `fetch` method receives the clients `callCluster`, `esClient` and `soClient` scoped to the user who performed the HTTP API request. Alternatively, when requesting the usage data to be reported to the Remote Telemetry Service, the clients are scoped to the internal Kibana user (`kibana_system`). Please, mind it might have lower-level access than the default super-admin `elastic` test user. +In some scenarios, your collector might need to maintain its own client. An example of that is the `monitoring` plugin, that maintains a connection to the Remote Monitoring Cluster to push its monitoring data. If that's the case, your plugin can opt-in to receive the additional `kibanaRequest` parameter by adding `extendFetchContext.kibanaRequest: true` to the collector's config: it will be appended to the context of the `fetch` method only if the request needs to be scoped to a user other than Kibana Internal, so beware that your collector will need to work for both scenarios (especially for the scenario when `kibanaRequest` is missing). Note: there will be many cases where you won't need to use the `callCluster`, `esClient` or `soClient` function that gets passed in to your `fetch` method at all. Your feature might have an accumulating value in server memory, or read something from the OS. @@ -105,7 +105,7 @@ In the case of using a custom SavedObjects client, it is up to the plugin to ini ```ts // server/plugin.ts import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; -import { CoreSetup, CoreStart } from 'kibana/server'; +import { CoreSetup, CoreStart } from 'src/core/server'; class Plugin { private savedObjectsRepository?: ISavedObjectsRepository; diff --git a/src/plugins/usage_collection/server/collector/collector.ts b/src/plugins/usage_collection/server/collector/collector.ts index c04b087d4adf5..797fdaa06a620 100644 --- a/src/plugins/usage_collection/server/collector/collector.ts +++ b/src/plugins/usage_collection/server/collector/collector.ts @@ -23,7 +23,8 @@ import { ElasticsearchClient, ISavedObjectsRepository, SavedObjectsClientContract, -} from 'kibana/server'; + KibanaRequest, +} from 'src/core/server'; export type CollectorFormatForBulkUpload = (result: T) => { type: string; payload: U }; @@ -46,26 +47,71 @@ export type MakeSchemaFrom = { : RecursiveMakeSchemaFrom[Key]>; }; -export interface CollectorFetchContext { +/** + * The context for the `fetch` method: It includes the most commonly used clients in the collectors (ES and SO clients). + * Both are scoped based on the request and the context: + * - When users are requesting a sample of data, it is scoped to their role to avoid exposing data they shouldn't read + * - When building the telemetry data payload to report to the remote cluster, the requests are scoped to the `kibana` internal user + * + * @remark Bear in mind when testing your collector that your user has the same privileges as the Kibana Internal user to ensure the expected data is sent to the remote cluster. + */ +export type CollectorFetchContext = { /** - * @depricated Scoped Legacy Elasticsearch client: use esClient instead + * @deprecated Scoped Legacy Elasticsearch client: use esClient instead */ callCluster: LegacyAPICaller; /** - * Request-scoped Elasticsearch client: - * - When users are requesting a sample of data, it is scoped to their role to avoid exposing data they should't read - * - When building the telemetry data payload to report to the remote cluster, the requests are scoped to the `kibana` internal user + * Request-scoped Elasticsearch client + * @remark Bear in mind when testing your collector that your user has the same privileges as the Kibana Internal user to ensure the expected data is sent to the remote cluster (more info: {@link CollectorFetchContext}) */ esClient: ElasticsearchClient; /** - * Request-scoped Saved Objects client: - * - When users are requesting a sample of data, it is scoped to their role to avoid exposing data they should't read - * - When building the telemetry data payload to report to the remote cluster, the requests are scoped to the `kibana` internal user + * Request-scoped Saved Objects client + * @remark Bear in mind when testing your collector that your user has the same privileges as the Kibana Internal user to ensure the expected data is sent to the remote cluster (more info: {@link CollectorFetchContext}) */ soClient: SavedObjectsClientContract | ISavedObjectsRepository; +} & (WithKibanaRequest extends true + ? { + /** + * The KibanaRequest that can be used to scope the requests: + * It is provided only when your custom clients need to be scoped. If not available, you should use the Internal Client. + * More information about when scoping is needed: {@link CollectorFetchContext} + * @remark You should only use this if you implement your collector to deal with both scenarios: when provided and, especially, when not provided. When telemetry payload is sent to the remote service the `kibanaRequest` will not be provided. + */ + kibanaRequest?: KibanaRequest; + } + : {}); + +export type CollectorFetchMethod< + WithKibanaRequest extends boolean | undefined, + TReturn, + ExtraOptions extends object = {} +> = ( + this: Collector & ExtraOptions, // Specify the context of `this` for this.log and others to become available + context: CollectorFetchContext +) => Promise | TReturn; + +export interface ICollectorOptionsFetchExtendedContext { + /** + * Set to `true` if your `fetch` method requires the `KibanaRequest` object to be added in its context {@link CollectorFetchContextWithRequest}. + * @remark You should fully understand acknowledge that by using the `KibanaRequest` in your collector, you need to ensure it should specially work without it because it won't be provided when building the telemetry payload actually sent to the remote telemetry service. + */ + kibanaRequest?: WithKibanaRequest; } -export interface CollectorOptions { +export type CollectorOptionsFetchExtendedContext< + WithKibanaRequest extends boolean +> = ICollectorOptionsFetchExtendedContext & + (WithKibanaRequest extends true // If enforced to true via Types, the config must be expected + ? Required, 'kibanaRequest'>> + : {}); + +export type CollectorOptions< + TFetchReturn = unknown, + UFormatBulkUploadPayload = TFetchReturn, // TODO: Once we remove bulk_uploader's dependency on usageCollection, we'll be able to remove this type + WithKibanaRequest extends boolean = boolean, + ExtraOptions extends object = {} +> = { /** * Unique string identifier for the collector */ @@ -78,23 +124,42 @@ export interface CollectorOptions { /** * Schema definition of the output of the `fetch` method. */ - schema?: MakeSchemaFrom; - fetch: (collectorFetchContext: CollectorFetchContext) => Promise | T; - /* + schema?: MakeSchemaFrom; + /** + * The method that will collect and return the data in the final format. + * @param collectorFetchContext {@link CollectorFetchContext} + */ + fetch: CollectorFetchMethod; + /** * A hook for allowing the fetched data payload to be organized into a typed * data model for internal bulk upload. See defaultFormatterForBulkUpload for * a generic example. * @deprecated Used only by the Legacy Monitoring collection (to be removed in 8.0) */ - formatForBulkUpload?: CollectorFormatForBulkUpload; -} + formatForBulkUpload?: CollectorFormatForBulkUpload; +} & ExtraOptions & + (WithKibanaRequest extends true // If enforced to true via Types, the config must be enforced + ? { + extendFetchContext: CollectorOptionsFetchExtendedContext; + } + : { + extendFetchContext?: CollectorOptionsFetchExtendedContext; + }); -export class Collector { - public readonly type: CollectorOptions['type']; - public readonly init?: CollectorOptions['init']; - public readonly fetch: CollectorOptions['fetch']; - private readonly _formatForBulkUpload?: CollectorFormatForBulkUpload; - public readonly isReady: CollectorOptions['isReady']; +export class Collector< + TFetchReturn, + UFormatBulkUploadPayload = TFetchReturn, + ExtraOptions extends object = {} +> { + public readonly extendFetchContext: CollectorOptionsFetchExtendedContext; + public readonly type: CollectorOptions['type']; + public readonly init?: CollectorOptions['init']; + public readonly fetch: CollectorFetchMethod; + public readonly isReady: CollectorOptions['isReady']; + private readonly _formatForBulkUpload?: CollectorFormatForBulkUpload< + TFetchReturn, + UFormatBulkUploadPayload + >; /* * @param {Object} logger - logger object * @param {String} options.type - property name as the key for the data @@ -105,8 +170,16 @@ export class Collector { * @param {Function} options.rest - optional other properties */ constructor( - protected readonly log: Logger, - { type, init, fetch, formatForBulkUpload, isReady, ...options }: CollectorOptions + public readonly log: Logger, + { + type, + init, + fetch, + formatForBulkUpload, + isReady, + extendFetchContext = {}, + ...options + }: CollectorOptions ) { if (type === undefined) { throw new Error('Collector must be instantiated with a options.type string property'); @@ -126,10 +199,11 @@ export class Collector { this.init = init; this.fetch = fetch; this.isReady = typeof isReady === 'function' ? isReady : () => true; + this.extendFetchContext = extendFetchContext; this._formatForBulkUpload = formatForBulkUpload; } - public formatForBulkUpload(result: T) { + public formatForBulkUpload(result: TFetchReturn) { if (this._formatForBulkUpload) { return this._formatForBulkUpload(result); } else { @@ -137,10 +211,10 @@ export class Collector { } } - protected defaultFormatterForBulkUpload(result: T) { + protected defaultFormatterForBulkUpload(result: TFetchReturn) { return { type: this.type, - payload: (result as unknown) as U, + payload: (result as unknown) as UFormatBulkUploadPayload, }; } } diff --git a/src/plugins/usage_collection/server/collector/collector_set.test.ts b/src/plugins/usage_collection/server/collector/collector_set.test.ts index 359a2d214f991..fc17ce131430c 100644 --- a/src/plugins/usage_collection/server/collector/collector_set.test.ts +++ b/src/plugins/usage_collection/server/collector/collector_set.test.ts @@ -47,6 +47,7 @@ describe('CollectorSet', () => { const mockCallCluster = jest.fn().mockResolvedValue({ passTest: 1000 }); const mockEsClient = elasticsearchServiceMock.createClusterClient().asInternalUser; const mockSoClient = savedObjectsRepositoryMock.create(); + const req = void 0; // No need to instantiate any KibanaRequest in these tests it('should throw an error if non-Collector type of object is registered', () => { const collectors = new CollectorSet({ logger }); @@ -93,7 +94,7 @@ describe('CollectorSet', () => { }) ); - const result = await collectors.bulkFetch(mockCallCluster, mockEsClient, mockSoClient); + const result = await collectors.bulkFetch(mockCallCluster, mockEsClient, mockSoClient, req); expect(loggerSpies.debug).toHaveBeenCalledTimes(1); expect(loggerSpies.debug).toHaveBeenCalledWith( 'Fetching data from MY_TEST_COLLECTOR collector' @@ -118,7 +119,7 @@ describe('CollectorSet', () => { let result; try { - result = await collectors.bulkFetch(mockCallCluster, mockEsClient, mockSoClient); + result = await collectors.bulkFetch(mockCallCluster, mockEsClient, mockSoClient, req); } catch (err) { // Do nothing } @@ -136,7 +137,7 @@ describe('CollectorSet', () => { }) ); - const result = await collectors.bulkFetch(mockCallCluster, mockEsClient, mockSoClient); + const result = await collectors.bulkFetch(mockCallCluster, mockEsClient, mockSoClient, req); expect(result).toStrictEqual([ { type: 'MY_TEST_COLLECTOR', @@ -154,7 +155,7 @@ describe('CollectorSet', () => { } as any) ); - const result = await collectors.bulkFetch(mockCallCluster, mockEsClient, mockSoClient); + const result = await collectors.bulkFetch(mockCallCluster, mockEsClient, mockSoClient, req); expect(result).toStrictEqual([ { type: 'MY_TEST_COLLECTOR', @@ -177,7 +178,7 @@ describe('CollectorSet', () => { }) ); - const result = await collectors.bulkFetch(mockCallCluster, mockEsClient, mockSoClient); + const result = await collectors.bulkFetch(mockCallCluster, mockEsClient, mockSoClient, req); expect(result).toStrictEqual([ { type: 'MY_TEST_COLLECTOR', @@ -274,4 +275,272 @@ describe('CollectorSet', () => { expect(collectors.isUsageCollector(void 0)).toEqual(false); }); }); + + describe('makeStatsCollector', () => { + const collectorSet = new CollectorSet({ logger }); + test('TS should hide kibanaRequest when not opted-in', () => { + collectorSet.makeStatsCollector({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + // @ts-expect-error + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + }); + }); + + test('TS should hide kibanaRequest when not opted-in (explicit false)', () => { + collectorSet.makeStatsCollector({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + // @ts-expect-error + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + extendFetchContext: { + kibanaRequest: false, + }, + }); + }); + + test('TS should allow using kibanaRequest when opted-in (explicit true)', () => { + collectorSet.makeStatsCollector({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + extendFetchContext: { + kibanaRequest: true, + }, + }); + }); + + test('fetch can use the logger (TS allows it)', () => { + const collector = collectorSet.makeStatsCollector({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch() { + this.log.info("I can use the Collector's class logger!"); + return { test: 1 }; + }, + }); + expect( + collector.fetch( + // @ts-expect-error: the test implementation is not using it + {} + ) + ).toStrictEqual({ test: 1 }); + }); + }); + + describe('makeUsageCollector', () => { + const collectorSet = new CollectorSet({ logger }); + describe('TS validations', () => { + describe('when types are inferred', () => { + test('TS should hide kibanaRequest when not opted-in', () => { + collectorSet.makeUsageCollector({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + // @ts-expect-error + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + }); + }); + + test('TS should hide kibanaRequest when not opted-in (explicit false)', () => { + collectorSet.makeUsageCollector({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + // @ts-expect-error + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + extendFetchContext: { + kibanaRequest: false, + }, + }); + }); + + test('TS should allow using kibanaRequest when opted-in (explicit true)', () => { + collectorSet.makeUsageCollector({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + extendFetchContext: { + kibanaRequest: true, + }, + }); + }); + }); + + describe('when types are explicit', () => { + test('TS should hide `kibanaRequest` from ctx when undefined or false', () => { + collectorSet.makeUsageCollector<{ test: number }>({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + // @ts-expect-error + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + }); + collectorSet.makeUsageCollector<{ test: number }, unknown, false>({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + // @ts-expect-error + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + extendFetchContext: { + kibanaRequest: false, + }, + }); + collectorSet.makeUsageCollector<{ test: number }, unknown, false>({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + // @ts-expect-error + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + }); + }); + test('TS should not allow `true` when types declare false', () => { + // false is the default when at least 1 type is specified + collectorSet.makeUsageCollector<{ test: number }>({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + // @ts-expect-error + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + extendFetchContext: { + // @ts-expect-error + kibanaRequest: true, + }, + }); + collectorSet.makeUsageCollector<{ test: number }, unknown, false>({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + // @ts-expect-error + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + extendFetchContext: { + // @ts-expect-error + kibanaRequest: true, + }, + }); + }); + + test('TS should allow `true` when types explicitly declare `true` and do not allow `false` or undefined', () => { + // false is the default when at least 1 type is specified + collectorSet.makeUsageCollector<{ test: number }, unknown, true>({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + extendFetchContext: { + kibanaRequest: true, + }, + }); + collectorSet.makeUsageCollector<{ test: number }, unknown, true>({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + extendFetchContext: { + // @ts-expect-error + kibanaRequest: false, + }, + }); + collectorSet.makeUsageCollector<{ test: number }, unknown, true>({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + extendFetchContext: { + // @ts-expect-error + kibanaRequest: undefined, + }, + }); + collectorSet.makeUsageCollector<{ test: number }, unknown, true>({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + // @ts-expect-error + extendFetchContext: {}, + }); + collectorSet.makeUsageCollector<{ test: number }, unknown, true>( + // @ts-expect-error + { + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch: (ctx) => { + const { kibanaRequest } = ctx; + return { test: kibanaRequest ? 1 : 0 }; + }, + } + ); + }); + }); + }); + + test('fetch can use the logger (TS allows it)', () => { + const collector = collectorSet.makeUsageCollector({ + type: 'MY_TEST_COLLECTOR', + isReady: () => true, + schema: { test: { type: 'long' } }, + fetch() { + this.log.info("I can use the Collector's class logger!"); + return { test: 1 }; + }, + }); + expect( + collector.fetch( + // @ts-expect-error: the test implementation is not using it + {} + ) + ).toStrictEqual({ test: 1 }); + }); + }); }); diff --git a/src/plugins/usage_collection/server/collector/collector_set.ts b/src/plugins/usage_collection/server/collector/collector_set.ts index c52830cda6513..fe4f3536ffed6 100644 --- a/src/plugins/usage_collection/server/collector/collector_set.ts +++ b/src/plugins/usage_collection/server/collector/collector_set.ts @@ -24,50 +24,79 @@ import { ElasticsearchClient, ISavedObjectsRepository, SavedObjectsClientContract, -} from 'kibana/server'; + KibanaRequest, +} from 'src/core/server'; import { Collector, CollectorOptions } from './collector'; import { UsageCollector, UsageCollectorOptions } from './usage_collector'; +type AnyCollector = Collector; +type AnyUsageCollector = UsageCollector; + interface CollectorSetConfig { logger: Logger; maximumWaitTimeForAllCollectorsInS?: number; - collectors?: Array>; + collectors?: AnyCollector[]; } export class CollectorSet { private _waitingForAllCollectorsTimestamp?: number; private readonly logger: Logger; private readonly maximumWaitTimeForAllCollectorsInS: number; - private readonly collectors: Map>; + private readonly collectors: Map; constructor({ logger, maximumWaitTimeForAllCollectorsInS, collectors = [] }: CollectorSetConfig) { this.logger = logger; this.collectors = new Map(collectors.map((collector) => [collector.type, collector])); this.maximumWaitTimeForAllCollectorsInS = maximumWaitTimeForAllCollectorsInS || 60; } + /** + * Instantiates a stats collector with the definition provided in the options + * @param options Definition of the collector {@link CollectorOptions} + */ public makeStatsCollector = < - T, - U, - O extends CollectorOptions = CollectorOptions // Used to allow extra properties (the Collector constructor extends the class with the additional options provided) + TFetchReturn, + TFormatForBulkUpload, + WithKibanaRequest extends boolean, + ExtraOptions extends object = {} >( - options: O + options: CollectorOptions ) => { - return new Collector(this.logger, options); + return new Collector(this.logger, options); }; + + /** + * Instantiates an usage collector with the definition provided in the options + * @param options Definition of the collector {@link CollectorOptions} + */ public makeUsageCollector = < - T, - U = T, - O extends UsageCollectorOptions = UsageCollectorOptions + TFetchReturn, + TFormatForBulkUpload = { usage: { [key: string]: TFetchReturn } }, + // TODO: Right now, users will need to explicitly claim `true` for TS to allow `kibanaRequest` usage. + // If we improve `telemetry-check-tools` so plugins do not need to specify TFetchReturn, + // we'll be able to remove the type defaults and TS will successfully infer the config value as provided in JS. + WithKibanaRequest extends boolean = false, + ExtraOptions extends object = {} >( - options: O + options: UsageCollectorOptions< + TFetchReturn, + TFormatForBulkUpload, + WithKibanaRequest, + ExtraOptions + > ) => { - return new UsageCollector(this.logger, options); + return new UsageCollector( + this.logger, + options + ); }; - /* - * @param collector {Collector} collector object + /** + * Registers a collector to be used when collecting all the usage and stats data + * @param collector Collector to be added to the set (previously created via `makeUsageCollector` or `makeStatsCollector`) */ - public registerCollector = (collector: Collector) => { + public registerCollector = ( + collector: Collector + ) => { // check instanceof if (!(collector instanceof Collector)) { throw new Error('CollectorSet can only have Collector instances registered'); @@ -89,7 +118,7 @@ export class CollectorSet { return [...this.collectors.values()].find((c) => c.type === type); }; - public isUsageCollector = (x: UsageCollector | any): x is UsageCollector => { + public isUsageCollector = (x: AnyUsageCollector | any): x is AnyUsageCollector => { return x instanceof UsageCollector; }; @@ -144,15 +173,22 @@ export class CollectorSet { callCluster: LegacyAPICaller, esClient: ElasticsearchClient, soClient: SavedObjectsClientContract | ISavedObjectsRepository, - collectors: Map> = this.collectors + kibanaRequest: KibanaRequest | undefined, // intentionally `| undefined` to enforce providing the parameter + collectors: Map = this.collectors ) => { const responses = await Promise.all( [...collectors.values()].map(async (collector) => { this.logger.debug(`Fetching data from ${collector.type} collector`); try { + const context = { + callCluster, + esClient, + soClient, + ...(collector.extendFetchContext.kibanaRequest && { kibanaRequest }), + }; return { type: collector.type, - result: await collector.fetch({ callCluster, esClient, soClient }), + result: await collector.fetch(context), }; } catch (err) { this.logger.warn(err); @@ -169,7 +205,7 @@ export class CollectorSet { /* * @return {new CollectorSet} */ - public getFilteredCollectorSet = (filter: (col: Collector) => boolean) => { + public getFilteredCollectorSet = (filter: (col: AnyCollector) => boolean) => { const filtered = [...this.collectors.values()].filter(filter); return this.makeCollectorSetFromArray(filtered); }; @@ -177,13 +213,15 @@ export class CollectorSet { public bulkFetchUsage = async ( callCluster: LegacyAPICaller, esClient: ElasticsearchClient, - savedObjectsClient: SavedObjectsClientContract | ISavedObjectsRepository + savedObjectsClient: SavedObjectsClientContract | ISavedObjectsRepository, + kibanaRequest: KibanaRequest | undefined // intentionally `| undefined` to enforce providing the parameter ) => { const usageCollectors = this.getFilteredCollectorSet((c) => c instanceof UsageCollector); return await this.bulkFetch( callCluster, esClient, savedObjectsClient, + kibanaRequest, usageCollectors.collectors ); }; @@ -239,7 +277,7 @@ export class CollectorSet { return [...this.collectors.values()].some(someFn); }; - private makeCollectorSetFromArray = (collectors: Collector[]) => { + private makeCollectorSetFromArray = (collectors: AnyCollector[]) => { return new CollectorSet({ logger: this.logger, maximumWaitTimeForAllCollectorsInS: this.maximumWaitTimeForAllCollectorsInS, diff --git a/src/plugins/usage_collection/server/collector/usage_collector.ts b/src/plugins/usage_collection/server/collector/usage_collector.ts index 5bfc36537e0b0..a042ea113d5cc 100644 --- a/src/plugins/usage_collection/server/collector/usage_collector.ts +++ b/src/plugins/usage_collection/server/collector/usage_collector.ts @@ -22,25 +22,39 @@ import { KIBANA_STATS_TYPE } from '../../common/constants'; import { Collector, CollectorOptions } from './collector'; // Enforce the `schema` property for UsageCollectors -export type UsageCollectorOptions = CollectorOptions & - Required, 'schema'>>; +export type UsageCollectorOptions< + TFetchReturn = unknown, + UFormatBulkUploadPayload = { usage: { [key: string]: TFetchReturn } }, + WithKibanaRequest extends boolean = false, + ExtraOptions extends object = {} +> = CollectorOptions & + Required, 'schema'>>; -export class UsageCollector extends Collector< - T, - U -> { - constructor(protected readonly log: Logger, collectorOptions: UsageCollectorOptions) { +export class UsageCollector< + TFetchReturn, + UFormatBulkUploadPayload = { usage: { [key: string]: TFetchReturn } }, + ExtraOptions extends object = {} +> extends Collector { + constructor( + public readonly log: Logger, + collectorOptions: UsageCollectorOptions< + TFetchReturn, + UFormatBulkUploadPayload, + any, + ExtraOptions + > + ) { super(log, collectorOptions); } - protected defaultFormatterForBulkUpload(result: T) { + protected defaultFormatterForBulkUpload(result: TFetchReturn) { return { type: KIBANA_STATS_TYPE, payload: ({ usage: { [this.type]: result, }, - } as unknown) as U, + } as unknown) as UFormatBulkUploadPayload, }; } } diff --git a/src/plugins/usage_collection/server/config.ts b/src/plugins/usage_collection/server/config.ts index 76379d9385cff..09b0e05025e63 100644 --- a/src/plugins/usage_collection/server/config.ts +++ b/src/plugins/usage_collection/server/config.ts @@ -18,7 +18,7 @@ */ import { schema, TypeOf } from '@kbn/config-schema'; -import { PluginConfigDescriptor } from 'kibana/server'; +import { PluginConfigDescriptor } from 'src/core/server'; import { DEFAULT_MAXIMUM_WAIT_TIME_FOR_ALL_COLLECTORS_IN_S } from '../common/constants'; export const configSchema = schema.object({ diff --git a/src/plugins/usage_collection/server/index.ts b/src/plugins/usage_collection/server/index.ts index f7a08fdb5e9dd..48ea9afa13976 100644 --- a/src/plugins/usage_collection/server/index.ts +++ b/src/plugins/usage_collection/server/index.ts @@ -17,7 +17,7 @@ * under the License. */ -import { PluginInitializerContext } from 'kibana/server'; +import { PluginInitializerContext } from 'src/core/server'; import { UsageCollectionPlugin } from './plugin'; export { diff --git a/src/plugins/usage_collection/server/mocks.ts b/src/plugins/usage_collection/server/mocks.ts index d08db1eaec0e1..3d89380f629dc 100644 --- a/src/plugins/usage_collection/server/mocks.ts +++ b/src/plugins/usage_collection/server/mocks.ts @@ -20,7 +20,7 @@ import { loggingSystemMock } from '../../../core/server/mocks'; import { UsageCollectionSetup } from './plugin'; import { CollectorSet } from './collector'; -export { createCollectorFetchContextMock } from './usage_collection.mock'; +export { Collector, createCollectorFetchContextMock } from './usage_collection.mock'; const createSetupContract = () => { return { diff --git a/src/plugins/usage_collection/server/plugin.ts b/src/plugins/usage_collection/server/plugin.ts index 74e70d5ea9d35..9a8876446d01e 100644 --- a/src/plugins/usage_collection/server/plugin.ts +++ b/src/plugins/usage_collection/server/plugin.ts @@ -25,7 +25,7 @@ import { CoreStart, ISavedObjectsRepository, Plugin, -} from 'kibana/server'; +} from 'src/core/server'; import { ConfigType } from './config'; import { CollectorSet } from './collector'; import { setupRoutes } from './routes'; diff --git a/src/plugins/usage_collection/server/report/store_report.ts b/src/plugins/usage_collection/server/report/store_report.ts index c40622831eeee..d9aac23fd1ff0 100644 --- a/src/plugins/usage_collection/server/report/store_report.ts +++ b/src/plugins/usage_collection/server/report/store_report.ts @@ -17,7 +17,7 @@ * under the License. */ -import { ISavedObjectsRepository, SavedObject } from 'kibana/server'; +import { ISavedObjectsRepository, SavedObject } from 'src/core/server'; import { ReportSchemaType } from './schema'; export async function storeReport( diff --git a/src/plugins/usage_collection/server/routes/index.ts b/src/plugins/usage_collection/server/routes/index.ts index b367ddc184be7..15d408ff3723b 100644 --- a/src/plugins/usage_collection/server/routes/index.ts +++ b/src/plugins/usage_collection/server/routes/index.ts @@ -22,7 +22,7 @@ import { ISavedObjectsRepository, MetricsServiceSetup, ServiceStatus, -} from 'kibana/server'; +} from 'src/core/server'; import { Observable } from 'rxjs'; import { CollectorSet } from '../collector'; import { registerUiMetricRoute } from './report_metrics'; diff --git a/src/plugins/usage_collection/server/routes/report_metrics.ts b/src/plugins/usage_collection/server/routes/report_metrics.ts index a72222968eabf..590c3340697b8 100644 --- a/src/plugins/usage_collection/server/routes/report_metrics.ts +++ b/src/plugins/usage_collection/server/routes/report_metrics.ts @@ -18,7 +18,7 @@ */ import { schema } from '@kbn/config-schema'; -import { IRouter, ISavedObjectsRepository } from 'kibana/server'; +import { IRouter, ISavedObjectsRepository } from 'src/core/server'; import { storeReport, reportSchema } from '../report'; export function registerUiMetricRoute( diff --git a/src/plugins/usage_collection/server/routes/stats/stats.ts b/src/plugins/usage_collection/server/routes/stats/stats.ts index d38250067053c..16a1c2c742f04 100644 --- a/src/plugins/usage_collection/server/routes/stats/stats.ts +++ b/src/plugins/usage_collection/server/routes/stats/stats.ts @@ -27,6 +27,7 @@ import { ElasticsearchClient, IRouter, ISavedObjectsRepository, + KibanaRequest, LegacyAPICaller, MetricsServiceSetup, SavedObjectsClientContract, @@ -67,9 +68,15 @@ export function registerStatsRoute({ const getUsage = async ( callCluster: LegacyAPICaller, esClient: ElasticsearchClient, - savedObjectsClient: SavedObjectsClientContract | ISavedObjectsRepository + savedObjectsClient: SavedObjectsClientContract | ISavedObjectsRepository, + kibanaRequest: KibanaRequest ): Promise => { - const usage = await collectorSet.bulkFetchUsage(callCluster, esClient, savedObjectsClient); + const usage = await collectorSet.bulkFetchUsage( + callCluster, + esClient, + savedObjectsClient, + kibanaRequest + ); return collectorSet.toObject(usage); }; @@ -115,7 +122,7 @@ export function registerStatsRoute({ } const usagePromise = shouldGetUsage - ? getUsage(callCluster, asCurrentUser, savedObjectsClient) + ? getUsage(callCluster, asCurrentUser, savedObjectsClient, req) : Promise.resolve({}); const [usage, clusterUuid] = await Promise.all([ usagePromise, diff --git a/src/plugins/usage_collection/server/usage_collection.mock.ts b/src/plugins/usage_collection/server/usage_collection.mock.ts index c31756c60e32d..05dae8fa85164 100644 --- a/src/plugins/usage_collection/server/usage_collection.mock.ts +++ b/src/plugins/usage_collection/server/usage_collection.mock.ts @@ -19,13 +19,17 @@ import { elasticsearchServiceMock, + httpServerMock, + loggingSystemMock, savedObjectsRepositoryMock, } from '../../../../src/core/server/mocks'; -import { CollectorOptions } from './collector/collector'; +import { CollectorOptions, Collector, UsageCollector } from './collector'; import { UsageCollectionSetup, CollectorFetchContext } from './index'; -export { CollectorOptions }; +export { CollectorOptions, Collector }; + +const logger = loggingSystemMock.createLogger(); export const createUsageCollectionSetupMock = () => { const usageCollectionSetupMock: jest.Mocked = { @@ -37,13 +41,13 @@ export const createUsageCollectionSetupMock = () => { // @ts-ignore jest.fn doesn't play nice with type guards isUsageCollector: jest.fn(), makeCollectorSetFromArray: jest.fn(), - makeStatsCollector: jest.fn(), map: jest.fn(), maximumWaitTimeForAllCollectorsInS: 0, some: jest.fn(), toApiFieldNames: jest.fn(), toObject: jest.fn(), - makeUsageCollector: jest.fn(), + makeStatsCollector: jest.fn().mockImplementation((cfg) => new Collector(logger, cfg)), + makeUsageCollector: jest.fn().mockImplementation((cfg) => new UsageCollector(logger, cfg)), registerCollector: jest.fn(), }; @@ -51,11 +55,23 @@ export const createUsageCollectionSetupMock = () => { return usageCollectionSetupMock; }; -export function createCollectorFetchContextMock(): jest.Mocked { - const collectorFetchClientsMock: jest.Mocked = { +export function createCollectorFetchContextMock(): jest.Mocked> { + const collectorFetchClientsMock: jest.Mocked> = { + callCluster: elasticsearchServiceMock.createLegacyClusterClient().callAsInternalUser, + esClient: elasticsearchServiceMock.createClusterClient().asInternalUser, + soClient: savedObjectsRepositoryMock.create(), + }; + return collectorFetchClientsMock; +} + +export function createCollectorFetchContextWithKibanaMock(): jest.Mocked< + CollectorFetchContext +> { + const collectorFetchClientsMock: jest.Mocked> = { callCluster: elasticsearchServiceMock.createLegacyClusterClient().callAsInternalUser, esClient: elasticsearchServiceMock.createClusterClient().asInternalUser, soClient: savedObjectsRepositoryMock.create(), + kibanaRequest: httpServerMock.createKibanaRequest(), }; return collectorFetchClientsMock; } diff --git a/src/plugins/vis_type_timelion/public/components/timelion_vis_component.tsx b/src/plugins/vis_type_timelion/public/components/timelion_vis_component.tsx index a448b58afe8a4..baf3365a514a6 100644 --- a/src/plugins/vis_type_timelion/public/components/timelion_vis_component.tsx +++ b/src/plugins/vis_type_timelion/public/components/timelion_vis_component.tsx @@ -33,6 +33,8 @@ import { SERIES_ID_ATTR, colors, Axis, + ACTIVE_CURSOR, + eventBus, } from '../helpers/panel_utils'; import { Series, Sheet } from '../helpers/timelion_request_handler'; @@ -338,16 +340,40 @@ function TimelionVisComponent({ }); }, [legendCaption, legendValueNumbers]); + const plotHover = useCallback( + (pos: Position) => { + (plot as CrosshairPlot).setCrosshair(pos); + debouncedSetLegendNumbers(pos); + }, + [plot, debouncedSetLegendNumbers] + ); + const plotHoverHandler = useCallback( (event: JQuery.TriggeredEvent, pos: Position) => { if (!plot) { return; } - (plot as CrosshairPlot).setCrosshair(pos); - debouncedSetLegendNumbers(pos); + plotHover(pos); + eventBus.trigger(ACTIVE_CURSOR, [event, pos]); }, - [plot, debouncedSetLegendNumbers] + [plot, plotHover] ); + + useEffect(() => { + const updateCursor = (_: any, event: JQuery.TriggeredEvent, pos: Position) => { + if (!plot) { + return; + } + plotHover(pos); + }; + + eventBus.on(ACTIVE_CURSOR, updateCursor); + + return () => { + eventBus.off(ACTIVE_CURSOR, updateCursor); + }; + }, [plot, plotHover]); + const mouseLeaveHandler = useCallback(() => { if (!plot) { return; diff --git a/src/plugins/vis_type_timelion/public/helpers/panel_utils.ts b/src/plugins/vis_type_timelion/public/helpers/panel_utils.ts index 860b4e9f2dbde..ba363cf30a079 100644 --- a/src/plugins/vis_type_timelion/public/helpers/panel_utils.ts +++ b/src/plugins/vis_type_timelion/public/helpers/panel_utils.ts @@ -18,6 +18,7 @@ */ import { cloneDeep, defaults, mergeWith, compact } from 'lodash'; +import $ from 'jquery'; import moment, { Moment } from 'moment-timezone'; import { TimefilterContract } from 'src/plugins/data/public'; @@ -50,6 +51,9 @@ interface TimeRangeBounds { max: Moment | undefined; } +export const ACTIVE_CURSOR = 'ACTIVE_CURSOR_TIMELION'; +export const eventBus = $({}); + const colors = [ '#01A4A4', '#C66', diff --git a/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js b/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js index c12e518a9dcd3..f936710bf2b81 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js +++ b/src/plugins/vis_type_timeseries/public/application/components/vis_types/timeseries/vis.js @@ -161,6 +161,10 @@ export class TimeseriesVisualization extends Component { const yAxis = []; let mainDomainAdded = false; + const allSeriesHaveSameFormatters = seriesModel.every( + (seriesGroup) => seriesGroup.formatter === seriesModel[0].formatter + ); + this.showToastNotification = null; seriesModel.forEach((seriesGroup) => { @@ -211,7 +215,7 @@ export class TimeseriesVisualization extends Component { }); } else if (!mainDomainAdded) { TimeseriesVisualization.addYAxis(yAxis, { - tickFormatter: series.length === 1 ? undefined : (val) => val, + tickFormatter: allSeriesHaveSameFormatters ? seriesGroupTickFormatter : (val) => val, id: yAxisIdGenerator('main'), groupId: mainAxisGroupId, position: model.axis_position, diff --git a/src/plugins/vis_type_timeseries/server/index.ts b/src/plugins/vis_type_timeseries/server/index.ts index 333ed0ff64fdb..1037dc81b2b17 100644 --- a/src/plugins/vis_type_timeseries/server/index.ts +++ b/src/plugins/vis_type_timeseries/server/index.ts @@ -43,7 +43,9 @@ export { AbstractSearchStrategy, ReqFacade, } from './lib/search_strategies/strategies/abstract_search_strategy'; -// @ts-ignore + +export { VisPayload } from '../common/types'; + export { DefaultSearchCapabilities } from './lib/search_strategies/default_search_capabilities'; export function plugin(initializerContext: PluginInitializerContext) { diff --git a/src/plugins/vis_type_timeseries/server/lib/get_fields.ts b/src/plugins/vis_type_timeseries/server/lib/get_fields.ts index dc49e280a2bb7..8f87318222f2b 100644 --- a/src/plugins/vis_type_timeseries/server/lib/get_fields.ts +++ b/src/plugins/vis_type_timeseries/server/lib/get_fields.ts @@ -38,7 +38,7 @@ export async function getFields( // removes the need to refactor many layers of dependencies on "req", and instead just augments the top // level object passed from here. The layers should be refactored fully at some point, but for now // this works and we are still using the New Platform services for these vis data portions. - const reqFacade: ReqFacade = { + const reqFacade: ReqFacade<{}> = { requestContext, ...request, framework, diff --git a/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts b/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts index 5eef2b53e2431..fcb66d2e12fd1 100644 --- a/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts +++ b/src/plugins/vis_type_timeseries/server/lib/get_vis_data.ts @@ -64,7 +64,7 @@ export function getVisData( // removes the need to refactor many layers of dependencies on "req", and instead just augments the top // level object passed from here. The layers should be refactored fully at some point, but for now // this works and we are still using the New Platform services for these vis data portions. - const reqFacade: ReqFacade = { + const reqFacade: ReqFacade = { requestContext, ...request, framework, diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.test.js b/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.test.ts similarity index 90% rename from src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.test.js rename to src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.test.ts index b9b7759711567..a570e02ada8d1 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.test.ts @@ -17,13 +17,15 @@ * under the License. */ import { DefaultSearchCapabilities } from './default_search_capabilities'; +import { ReqFacade } from './strategies/abstract_search_strategy'; +import { VisPayload } from '../../../common/types'; describe('DefaultSearchCapabilities', () => { - let defaultSearchCapabilities; - let req; + let defaultSearchCapabilities: DefaultSearchCapabilities; + let req: ReqFacade; beforeEach(() => { - req = {}; + req = {} as ReqFacade; defaultSearchCapabilities = new DefaultSearchCapabilities(req); }); @@ -45,13 +47,13 @@ describe('DefaultSearchCapabilities', () => { }); test('should return Search Timezone', () => { - defaultSearchCapabilities.request = { + defaultSearchCapabilities.request = ({ payload: { timerange: { timezone: 'UTC', }, }, - }; + } as unknown) as ReqFacade; expect(defaultSearchCapabilities.searchTimezone).toEqual('UTC'); }); diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.js b/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.ts similarity index 69% rename from src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.js rename to src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.ts index 02a710fef897f..73b701379aee0 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.js +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/default_search_capabilities.ts @@ -16,40 +16,43 @@ * specific language governing permissions and limitations * under the License. */ +import { Unit } from '@elastic/datemath'; import { convertIntervalToUnit, parseInterval, getSuitableUnit, } from '../vis_data/helpers/unit_to_seconds'; import { RESTRICTIONS_KEYS } from '../../../common/ui_restrictions'; +import { ReqFacade } from './strategies/abstract_search_strategy'; +import { VisPayload } from '../../../common/types'; -const getTimezoneFromRequest = (request) => { +const getTimezoneFromRequest = (request: ReqFacade) => { return request.payload.timerange.timezone; }; export class DefaultSearchCapabilities { - constructor(request, fieldsCapabilities = {}) { - this.request = request; - this.fieldsCapabilities = fieldsCapabilities; - } + constructor( + public request: ReqFacade, + public fieldsCapabilities: Record = {} + ) {} - get defaultTimeInterval() { + public get defaultTimeInterval() { return null; } - get whiteListedMetrics() { + public get whiteListedMetrics() { return this.createUiRestriction(); } - get whiteListedGroupByFields() { + public get whiteListedGroupByFields() { return this.createUiRestriction(); } - get whiteListedTimerangeModes() { + public get whiteListedTimerangeModes() { return this.createUiRestriction(); } - get uiRestrictions() { + public get uiRestrictions() { return { [RESTRICTIONS_KEYS.WHITE_LISTED_METRICS]: this.whiteListedMetrics, [RESTRICTIONS_KEYS.WHITE_LISTED_GROUP_BY_FIELDS]: this.whiteListedGroupByFields, @@ -57,36 +60,36 @@ export class DefaultSearchCapabilities { }; } - get searchTimezone() { + public get searchTimezone() { return getTimezoneFromRequest(this.request); } - createUiRestriction(restrictionsObject) { + createUiRestriction(restrictionsObject?: Record) { return { '*': !restrictionsObject, ...(restrictionsObject || {}), }; } - parseInterval(interval) { + parseInterval(interval: string) { return parseInterval(interval); } - getSuitableUnit(intervalInSeconds) { + getSuitableUnit(intervalInSeconds: string | number) { return getSuitableUnit(intervalInSeconds); } - convertIntervalToUnit(intervalString, unit) { + convertIntervalToUnit(intervalString: string, unit: Unit) { const parsedInterval = this.parseInterval(intervalString); - if (parsedInterval.unit !== unit) { + if (parsedInterval?.unit !== unit) { return convertIntervalToUnit(intervalString, unit); } return parsedInterval; } - getValidTimeInterval(intervalString) { + getValidTimeInterval(intervalString: string) { // Default search capabilities doesn't have any restrictions for the interval string return intervalString; } diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/search_strategies_registry.test.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/search_strategies_registry.test.ts index 66ea4f017dd90..4c3dcbd17bbd9 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/search_strategies_registry.test.ts +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/search_strategies_registry.test.ts @@ -27,10 +27,10 @@ import { DefaultSearchCapabilities } from './default_search_capabilities'; class MockSearchStrategy extends AbstractSearchStrategy { checkForViability() { - return { + return Promise.resolve({ isViable: true, capabilities: {}, - }; + }); } } @@ -65,7 +65,7 @@ describe('SearchStrategyRegister', () => { }); test('should add a strategy if it is an instance of AbstractSearchStrategy', () => { - const anotherSearchStrategy = new MockSearchStrategy('es'); + const anotherSearchStrategy = new MockSearchStrategy(); const addedStrategies = registry.addStrategy(anotherSearchStrategy); expect(addedStrategies.length).toEqual(2); @@ -75,7 +75,7 @@ describe('SearchStrategyRegister', () => { test('should return a MockSearchStrategy instance', async () => { const req = {}; const indexPattern = '*'; - const anotherSearchStrategy = new MockSearchStrategy('es'); + const anotherSearchStrategy = new MockSearchStrategy(); registry.addStrategy(anotherSearchStrategy); const { searchStrategy, capabilities } = (await registry.getViableStrategy(req, indexPattern))!; diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts index b1e21edf8b588..71461d319f2b6 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/abstract_search_strategy.ts @@ -46,16 +46,8 @@ export interface ReqFacade extends FakeRequest { getEsShardTimeout: () => Promise; } -export class AbstractSearchStrategy { - public indexType?: string; - public additionalParams: any; - - constructor(type?: string, additionalParams: any = {}) { - this.indexType = type; - this.additionalParams = additionalParams; - } - - async search(req: ReqFacade, bodies: any[], options = {}) { +export abstract class AbstractSearchStrategy { + async search(req: ReqFacade, bodies: any[], indexType?: string) { const requests: any[] = []; const { sessionId } = req.payload; @@ -64,15 +56,13 @@ export class AbstractSearchStrategy { req.requestContext .search!.search( { + indexType, params: { ...body, - ...this.additionalParams, }, - indexType: this.indexType, }, { sessionId, - ...options, } ) .toPromise() @@ -81,7 +71,18 @@ export class AbstractSearchStrategy { return Promise.all(requests); } - async getFieldsForWildcard(req: ReqFacade, indexPattern: string, capabilities: any) { + checkForViability( + req: ReqFacade, + indexPattern: string + ): Promise<{ isViable: boolean; capabilities: unknown }> { + throw new TypeError('Must override method'); + } + + async getFieldsForWildcard( + req: ReqFacade, + indexPattern: string, + capabilities?: unknown + ) { const { indexPatternsService } = req.pre; return await indexPatternsService!.getFieldsForWildcard({ @@ -89,11 +90,4 @@ export class AbstractSearchStrategy { fieldCapsOptions: { allow_no_indices: true }, }); } - - checkForViability( - req: ReqFacade, - indexPattern: string - ): { isViable: boolean; capabilities: any } { - throw new TypeError('Must override method'); - } } diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.test.js b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.test.ts similarity index 79% rename from src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.test.js rename to src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.test.ts index a9994ba3e1f75..d8ea6c9c8a526 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.test.ts @@ -17,13 +17,15 @@ * under the License. */ import { DefaultSearchStrategy } from './default_search_strategy'; +import { ReqFacade } from './abstract_search_strategy'; +import { VisPayload } from '../../../../common/types'; describe('DefaultSearchStrategy', () => { - let defaultSearchStrategy; - let req; + let defaultSearchStrategy: DefaultSearchStrategy; + let req: ReqFacade; beforeEach(() => { - req = {}; + req = {} as ReqFacade; defaultSearchStrategy = new DefaultSearchStrategy(); }); @@ -34,8 +36,8 @@ describe('DefaultSearchStrategy', () => { expect(defaultSearchStrategy.getFieldsForWildcard).toBeDefined(); }); - test('should check a strategy for viability', () => { - const value = defaultSearchStrategy.checkForViability(req); + test('should check a strategy for viability', async () => { + const value = await defaultSearchStrategy.checkForViability(req); expect(value.isViable).toBe(true); expect(value.capabilities).toEqual({ diff --git a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.js b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.ts similarity index 82% rename from src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.js rename to src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.ts index 8e57c117637bf..e1f519456d373 100644 --- a/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.js +++ b/src/plugins/vis_type_timeseries/server/lib/search_strategies/strategies/default_search_strategy.ts @@ -17,16 +17,17 @@ * under the License. */ -import { AbstractSearchStrategy } from './abstract_search_strategy'; +import { AbstractSearchStrategy, ReqFacade } from './abstract_search_strategy'; import { DefaultSearchCapabilities } from '../default_search_capabilities'; +import { VisPayload } from '../../../../common/types'; export class DefaultSearchStrategy extends AbstractSearchStrategy { name = 'default'; - checkForViability(req) { - return { + checkForViability(req: ReqFacade) { + return Promise.resolve({ isViable: true, capabilities: new DefaultSearchCapabilities(req), - }; + }); } } diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.js index 53f0b84b8ec3b..c021ba3cebc66 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/get_bucket_size.js @@ -42,14 +42,18 @@ const calculateBucketData = (timeInterval, capabilities) => { } // Check decimal - if (parsedInterval.value % 1 !== 0) { + if (parsedInterval && parsedInterval.value % 1 !== 0) { if (parsedInterval.unit !== 'ms') { - const { value, unit } = convertIntervalToUnit( + const converted = convertIntervalToUnit( intervalString, ASCENDING_UNIT_ORDER[ASCENDING_UNIT_ORDER.indexOf(parsedInterval.unit) - 1] ); - intervalString = value + unit; + if (converted) { + intervalString = converted.value + converted.unit; + } + + intervalString = undefined; } else { intervalString = '1ms'; } diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.test.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.test.ts similarity index 86% rename from src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.test.js rename to src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.test.ts index 5b533178949f1..278e557209a21 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.test.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.test.ts @@ -16,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +import { Unit } from '@elastic/datemath'; import { getUnitValue, @@ -51,22 +52,13 @@ describe('unit_to_seconds', () => { })); test('should not parse "gm" interval (negative)', () => - expect(parseInterval('gm')).toEqual({ - value: undefined, - unit: undefined, - })); + expect(parseInterval('gm')).toBeUndefined()); test('should not parse "-1d" interval (negative)', () => - expect(parseInterval('-1d')).toEqual({ - value: undefined, - unit: undefined, - })); + expect(parseInterval('-1d')).toBeUndefined()); test('should not parse "M" interval (negative)', () => - expect(parseInterval('M')).toEqual({ - value: undefined, - unit: undefined, - })); + expect(parseInterval('M')).toBeUndefined()); }); describe('convertIntervalToUnit()', () => { @@ -95,16 +87,10 @@ describe('unit_to_seconds', () => { })); test('should not convert "30m" interval to "0" unit (positive)', () => - expect(convertIntervalToUnit('30m', 'o')).toEqual({ - value: undefined, - unit: undefined, - })); + expect(convertIntervalToUnit('30m', 'o' as Unit)).toBeUndefined()); test('should not convert "m" interval to "s" unit (positive)', () => - expect(convertIntervalToUnit('m', 's')).toEqual({ - value: undefined, - unit: undefined, - })); + expect(convertIntervalToUnit('m', 's')).toBeUndefined()); }); describe('getSuitableUnit()', () => { @@ -155,8 +141,5 @@ describe('unit_to_seconds', () => { expect(getSuitableUnit(stringValue)).toBeUndefined(); }); - - test('should return "undefined" in case of no input value(negative)', () => - expect(getSuitableUnit()).toBeUndefined()); }); }); diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.ts similarity index 60% rename from src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.js rename to src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.ts index be8f1741627ba..8950e05c85d4f 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/unit_to_seconds.ts @@ -16,12 +16,15 @@ * specific language governing permissions and limitations * under the License. */ -import { INTERVAL_STRING_RE } from '../../../../common/interval_regexp'; import { sortBy, isNumber } from 'lodash'; +import { Unit } from '@elastic/datemath'; + +/** @ts-ignore */ +import { INTERVAL_STRING_RE } from '../../../../common/interval_regexp'; export const ASCENDING_UNIT_ORDER = ['ms', 's', 'm', 'h', 'd', 'w', 'M', 'y']; -const units = { +const units: Record = { ms: 0.001, s: 1, m: 60, @@ -32,49 +35,53 @@ const units = { y: 86400 * 7 * 4 * 12, // Leap year? }; -const sortedUnits = sortBy(Object.keys(units), (key) => units[key]); +const sortedUnits = sortBy(Object.keys(units), (key: Unit) => units[key]); -export const parseInterval = (intervalString) => { - let value; - let unit; +interface ParsedInterval { + value: number; + unit: Unit; +} +export const parseInterval = (intervalString: string): ParsedInterval | undefined => { if (intervalString) { const matches = intervalString.match(INTERVAL_STRING_RE); if (matches) { - value = Number(matches[1]); - unit = matches[2]; + return { + value: Number(matches[1]), + unit: matches[2] as Unit, + }; } } - - return { value, unit }; }; -export const convertIntervalToUnit = (intervalString, newUnit) => { +export const convertIntervalToUnit = ( + intervalString: string, + newUnit: Unit +): ParsedInterval | undefined => { const parsedInterval = parseInterval(intervalString); - let value; - let unit; - if (parsedInterval.value && units[newUnit]) { - value = Number( - ((parsedInterval.value * units[parsedInterval.unit]) / units[newUnit]).toFixed(2) - ); - unit = newUnit; + if (parsedInterval && units[newUnit]) { + return { + value: Number( + ((parsedInterval.value * units[parsedInterval.unit!]) / units[newUnit]).toFixed(2) + ), + unit: newUnit, + }; } - - return { value, unit }; }; -export const getSuitableUnit = (intervalInSeconds) => +export const getSuitableUnit = (intervalInSeconds: string | number) => sortedUnits.find((key, index, array) => { - const nextUnit = array[index + 1]; + const nextUnit = array[index + 1] as Unit; const isValidInput = isNumber(intervalInSeconds) && intervalInSeconds > 0; const isLastItem = index + 1 === array.length; return ( isValidInput && - ((intervalInSeconds >= units[key] && intervalInSeconds < units[nextUnit]) || isLastItem) + ((intervalInSeconds >= units[key as Unit] && intervalInSeconds < units[nextUnit]) || + isLastItem) ); - }); + }) as Unit; -export const getUnitValue = (unit) => units[unit]; +export const getUnitValue = (unit: Unit) => units[unit]; diff --git a/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.test.ts b/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.test.ts index e092fc8acfd71..fbef55df39719 100644 --- a/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.test.ts +++ b/src/plugins/vis_type_vega/server/usage_collector/register_vega_collector.test.ts @@ -59,9 +59,9 @@ describe('registerVegaUsageCollector', () => { it('makeUsageCollector config.fetch calls getStats', async () => { const mockCollectorSet = createUsageCollectionSetupMock(); registerVegaUsageCollector(mockCollectorSet, mockConfig, mockDeps); - const usageCollectorConfig = mockCollectorSet.makeUsageCollector.mock.calls[0][0]; + const usageCollector = mockCollectorSet.makeUsageCollector.mock.results[0].value; const mockedCollectorFetchContext = createCollectorFetchContextMock(); - const fetchResult = await usageCollectorConfig.fetch(mockedCollectorFetchContext); + const fetchResult = await usageCollector.fetch(mockedCollectorFetchContext); expect(mockGetStats).toBeCalledTimes(1); expect(mockGetStats).toBeCalledWith( mockedCollectorFetchContext.callCluster, diff --git a/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.test.ts b/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.test.ts index 7789e3de13e5a..380a86e15aa51 100644 --- a/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.test.ts +++ b/src/plugins/visualizations/server/usage_collector/register_visualizations_collector.test.ts @@ -58,9 +58,9 @@ describe('registerVisualizationsCollector', () => { it('makeUsageCollector config.fetch calls getStats', async () => { const mockCollectorSet = createUsageCollectionSetupMock(); registerVisualizationsCollector(mockCollectorSet, mockConfig); - const usageCollectorConfig = mockCollectorSet.makeUsageCollector.mock.calls[0][0]; + const usageCollector = mockCollectorSet.makeUsageCollector.mock.results[0].value; const mockCollectorFetchContext = createCollectorFetchContextMock(); - const fetchResult = await usageCollectorConfig.fetch(mockCollectorFetchContext); + const fetchResult = await usageCollector.fetch(mockCollectorFetchContext); expect(mockGetStats).toBeCalledTimes(1); expect(mockGetStats).toBeCalledWith(mockCollectorFetchContext.callCluster, mockIndex); expect(fetchResult).toBe(mockStats); diff --git a/test/common/config.js b/test/common/config.js index 9d6d531ae4b37..6c7d64e3e0bc0 100644 --- a/test/common/config.js +++ b/test/common/config.js @@ -61,6 +61,10 @@ export default function () { `--plugin-path=${path.join(__dirname, 'fixtures', 'plugins', 'newsfeed')}`, `--newsfeed.service.urlRoot=${servers.kibana.protocol}://${servers.kibana.hostname}:${servers.kibana.port}`, `--newsfeed.service.pathTemplate=/api/_newsfeed-FTS-external-service-simulators/kibana/v{VERSION}.json`, + // code coverage reporting plugin + ...(!!process.env.CODE_COVERAGE + ? [`--plugin-path=${path.join(__dirname, 'fixtures', 'plugins', 'coverage')}`] + : []), ], }, services, diff --git a/test/common/fixtures/plugins/coverage/kibana.json b/test/common/fixtures/plugins/coverage/kibana.json new file mode 100644 index 0000000000000..d80432534d746 --- /dev/null +++ b/test/common/fixtures/plugins/coverage/kibana.json @@ -0,0 +1,6 @@ +{ + "id": "coverage-fixtures", + "version": "kibana", + "server": false, + "ui": true +} \ No newline at end of file diff --git a/test/common/fixtures/plugins/coverage/public/index.ts b/test/common/fixtures/plugins/coverage/public/index.ts new file mode 100644 index 0000000000000..ed164c2d6bb94 --- /dev/null +++ b/test/common/fixtures/plugins/coverage/public/index.ts @@ -0,0 +1,24 @@ +/* + * 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 { CodeCoverageReportingPlugin } from './plugin'; + +export function plugin() { + return new CodeCoverageReportingPlugin(); +} diff --git a/test/common/fixtures/plugins/coverage/public/plugin.ts b/test/common/fixtures/plugins/coverage/public/plugin.ts new file mode 100644 index 0000000000000..e4da6b257de9a --- /dev/null +++ b/test/common/fixtures/plugins/coverage/public/plugin.ts @@ -0,0 +1,43 @@ +/* + * 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 { Plugin } from 'kibana/server'; + +declare global { + interface Window { + __coverage__: any; + flushCoverageToLog: any; + } +} + +export class CodeCoverageReportingPlugin implements Plugin { + constructor() {} + + public start() {} + + public setup() { + window.flushCoverageToLog = function () { + if (window.__coverage__) { + // eslint-disable-next-line no-console + console.log('coveragejson:' + btoa(JSON.stringify(window.__coverage__))); + } + }; + window.addEventListener('beforeunload', window.flushCoverageToLog); + } +} diff --git a/test/functional/services/listing_table.ts b/test/functional/services/listing_table.ts index 53b45697136ed..c9f2b8369783c 100644 --- a/test/functional/services/listing_table.ts +++ b/test/functional/services/listing_table.ts @@ -62,6 +62,20 @@ export function ListingTableProvider({ getService, getPageObjects }: FtrProvider return visualizationNames; } + public async waitUntilTableIsLoaded() { + return retry.try(async () => { + const isLoaded = await find.existsByDisplayedByCssSelector( + '[data-test-subj="itemsInMemTable"]:not(.euiBasicTable-loading)' + ); + + if (isLoaded) { + return true; + } else { + throw new Error('Waiting'); + } + }); + } + /** * Navigates through all pages on Landing page and returns array of items names */ diff --git a/test/scripts/jenkins_build_plugins.sh b/test/scripts/jenkins_build_plugins.sh index 59df02d401167..cfb829ea2db54 100755 --- a/test/scripts/jenkins_build_plugins.sh +++ b/test/scripts/jenkins_build_plugins.sh @@ -7,5 +7,6 @@ node scripts/build_kibana_platform_plugins \ --oss \ --scan-dir "$KIBANA_DIR/test/plugin_functional/plugins" \ --scan-dir "$KIBANA_DIR/test/interpreter_functional/plugins" \ + --scan-dir "$KIBANA_DIR/test/common/fixtures/plugins" \ --workers 6 \ --verbose diff --git a/test/scripts/jenkins_xpack_build_plugins.sh b/test/scripts/jenkins_xpack_build_plugins.sh index 289e64f66c89b..37b6398598788 100755 --- a/test/scripts/jenkins_xpack_build_plugins.sh +++ b/test/scripts/jenkins_xpack_build_plugins.sh @@ -5,6 +5,7 @@ source src/dev/ci_setup/setup_env.sh echo " -> building kibana platform plugins" node scripts/build_kibana_platform_plugins \ --scan-dir "$KIBANA_DIR/test/plugin_functional/plugins" \ + --scan-dir "$KIBANA_DIR/test/common/fixtures/plugins" \ --scan-dir "$XPACK_DIR/test/plugin_functional/plugins" \ --scan-dir "$XPACK_DIR/test/functional_with_es_ssl/fixtures/plugins" \ --scan-dir "$XPACK_DIR/test/alerting_api_integration/plugins" \ diff --git a/vars/kibanaPipeline.groovy b/vars/kibanaPipeline.groovy index eea3ff18f3453..0051293704717 100644 --- a/vars/kibanaPipeline.groovy +++ b/vars/kibanaPipeline.groovy @@ -390,12 +390,7 @@ def scriptTaskDocker(description, script) { def buildDocker() { sh( - script: """ - cp /usr/local/bin/runbld .ci/ - cp /usr/local/bin/bash_standard_lib.sh .ci/ - cd .ci - docker build -t kibana-ci -f ./Dockerfile . - """, + script: "./.ci/build_docker.sh", label: 'Build CI Docker image' ) } diff --git a/x-pack/.i18nrc.json b/x-pack/.i18nrc.json index 2be68b797ba5f..6937862d20536 100644 --- a/x-pack/.i18nrc.json +++ b/x-pack/.i18nrc.json @@ -38,10 +38,11 @@ "xpack.maps": ["plugins/maps"], "xpack.ml": ["plugins/ml"], "xpack.monitoring": ["plugins/monitoring"], - "xpack.remoteClusters": "plugins/remote_clusters", "xpack.painlessLab": "plugins/painless_lab", + "xpack.remoteClusters": "plugins/remote_clusters", "xpack.reporting": ["plugins/reporting"], "xpack.rollupJobs": ["plugins/rollup"], + "xpack.runtimeFields": "plugins/runtime_fields", "xpack.searchProfiler": "plugins/searchprofiler", "xpack.security": "plugins/security", "xpack.server": "legacy/server", diff --git a/x-pack/plugins/index_management/kibana.json b/x-pack/plugins/index_management/kibana.json index ff6a71d53894a..4e4ad9b8e1d31 100644 --- a/x-pack/plugins/index_management/kibana.json +++ b/x-pack/plugins/index_management/kibana.json @@ -18,6 +18,7 @@ "configPath": ["xpack", "index_management"], "requiredBundles": [ "kibanaReact", - "esUiShared" + "esUiShared", + "runtimeFields" ] } diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/painless_script_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/painless_script_parameter.tsx index 19746034b530c..9042e7f6ee328 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/painless_script_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/painless_script_parameter.tsx @@ -6,6 +6,7 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; +import { PainlessLang } from '@kbn/monaco'; import { EuiFormRow, EuiDescribedFormGroup } from '@elastic/eui'; import { CodeEditor, UseField } from '../../../shared_imports'; @@ -18,7 +19,7 @@ interface Props { export const PainlessScriptParameter = ({ stack }: Props) => { return ( - + path="script.source" config={getFieldConfig('script')}> {(scriptField) => { const error = scriptField.getErrorsMessages(); const isInvalid = error ? Boolean(error.length) : false; @@ -26,11 +27,10 @@ export const PainlessScriptParameter = ({ stack }: Props) => { const field = ( { return ( - + + path="runtime_type" + config={getFieldConfig('runtime_type')} + > {(runtimeTypeField) => { const { label, value, setValue } = runtimeTypeField; const typeDefinition = @@ -44,8 +47,14 @@ export const RuntimeTypeParameter = ({ stack }: Props) => { )} singleSelection={{ asPlainText: true }} options={RUNTIME_FIELD_OPTIONS} - selectedOptions={value as EuiComboBoxOptionOption[]} - onChange={setValue} + selectedOptions={value} + onChange={(newValue) => { + if (newValue.length === 0) { + // Don't allow clearing the type. One must always be selected + return; + } + setValue(newValue); + }} isClearable={false} fullWidth /> diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx index 25fdac5089b86..46292b7b2d357 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx @@ -28,35 +28,6 @@ export const FIELD_TYPES_OPTIONS = Object.entries(MAIN_DATA_TYPE_DEFINITION).map }) ) as ComboBoxOption[]; -export const RUNTIME_FIELD_OPTIONS = [ - { - label: 'Keyword', - value: 'keyword', - }, - { - label: 'Long', - value: 'long', - }, - { - label: 'Double', - value: 'double', - }, - { - label: 'Date', - value: 'date', - }, - { - label: 'IP', - value: 'ip', - }, - { - label: 'Boolean', - value: 'boolean', - }, -] as ComboBoxOption[]; - -export const RUNTIME_FIELD_TYPES = ['keyword', 'long', 'double', 'date', 'ip', 'boolean'] as const; - interface SuperSelectOptionConfig { inputDisplay: string; dropdownDisplay: JSX.Element; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx index 1434b7d4b4429..64f84ee2611a0 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx @@ -16,11 +16,12 @@ import { ValidationFuncArg, fieldFormatters, FieldConfig, + RUNTIME_FIELD_OPTIONS, + RuntimeType, } from '../shared_imports'; import { AliasOption, DataType, - RuntimeType, ComboBoxOption, ParameterName, ParameterDefinition, @@ -28,7 +29,6 @@ import { import { documentationService } from '../../../services/documentation'; import { INDEX_DEFAULT } from './default_values'; import { TYPE_DEFINITION } from './data_types_definition'; -import { RUNTIME_FIELD_OPTIONS } from './field_options'; const { toInt } = fieldFormatters; const { emptyField, containsCharsField, numberGreaterThanField, isJsonField } = fieldValidators; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts index 54b2486108183..68b40e876f655 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts @@ -53,3 +53,5 @@ export { } from '../../../../../../../src/plugins/es_ui_shared/public'; export { CodeEditor } from '../../../../../../../src/plugins/kibana_react/public'; + +export { RUNTIME_FIELD_OPTIONS, RuntimeType } from '../../../../../runtime_fields/public'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/types/document_fields.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/types/document_fields.ts index ee4dd55a5801f..b143eedd4f9d4 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/types/document_fields.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/types/document_fields.ts @@ -8,7 +8,7 @@ import { ReactNode } from 'react'; import { GenericObject } from './mappings_editor'; import { FieldConfig } from '../shared_imports'; -import { PARAMETERS_DEFINITION, RUNTIME_FIELD_TYPES } from '../constants'; +import { PARAMETERS_DEFINITION } from '../constants'; export interface DataTypeDefinition { label: string; @@ -76,8 +76,6 @@ export type SubType = NumericType | RangeType; export type DataType = MainType | SubType; -export type RuntimeType = typeof RUNTIME_FIELD_TYPES[number]; - export type NumericType = | 'long' | 'integer' diff --git a/x-pack/plugins/rollup/server/lib/search_strategies/index.ts b/x-pack/plugins/infra/common/http_api/host_details/index.ts similarity index 74% rename from x-pack/plugins/rollup/server/lib/search_strategies/index.ts rename to x-pack/plugins/infra/common/http_api/host_details/index.ts index 7db0b38ea29dd..b323ed8e9e327 100644 --- a/x-pack/plugins/rollup/server/lib/search_strategies/index.ts +++ b/x-pack/plugins/infra/common/http_api/host_details/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { registerRollupSearchStrategy } from './register_rollup_search_strategy'; +export * from './process_list'; diff --git a/x-pack/plugins/infra/common/http_api/host_details/process_list.ts b/x-pack/plugins/infra/common/http_api/host_details/process_list.ts new file mode 100644 index 0000000000000..4b4a0a54b9d13 --- /dev/null +++ b/x-pack/plugins/infra/common/http_api/host_details/process_list.ts @@ -0,0 +1,20 @@ +/* + * 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 * as rt from 'io-ts'; +import { MetricsAPITimerangeRT, MetricsAPISeriesRT } from '../metrics_api'; + +export const ProcessListAPIRequestRT = rt.type({ + hostTerm: rt.record(rt.string, rt.string), + timerange: MetricsAPITimerangeRT, + indexPattern: rt.string, +}); + +export const ProcessListAPIResponseRT = rt.array(MetricsAPISeriesRT); + +export type ProcessListAPIRequest = rt.TypeOf; + +export type ProcessListAPIResponse = rt.TypeOf; diff --git a/x-pack/plugins/infra/common/http_api/index.ts b/x-pack/plugins/infra/common/http_api/index.ts index 4c729d11ba8c1..914011454a732 100644 --- a/x-pack/plugins/infra/common/http_api/index.ts +++ b/x-pack/plugins/infra/common/http_api/index.ts @@ -11,3 +11,4 @@ export * from './metrics_explorer'; export * from './metrics_api'; export * from './log_alerts'; export * from './snapshot_api'; +export * from './host_details'; diff --git a/x-pack/plugins/infra/public/components/log_stream/index.tsx b/x-pack/plugins/infra/public/components/log_stream/index.tsx index 62a4d7ffc3d81..43d84497af9e9 100644 --- a/x-pack/plugins/infra/public/components/log_stream/index.tsx +++ b/x-pack/plugins/infra/public/components/log_stream/index.tsx @@ -4,9 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useMemo, useCallback } from 'react'; +import React, { useMemo, useCallback, useEffect } from 'react'; import { noop } from 'lodash'; -import useMount from 'react-use/lib/useMount'; import { euiStyled } from '../../../../observability/public'; import { LogEntriesCursor } from '../../../common/http_api'; @@ -100,10 +99,13 @@ Read more at https://github.com/elastic/kibana/blob/master/src/plugins/kibana_re const parsedHeight = typeof height === 'number' ? `${height}px` : height; // Component lifetime - useMount(() => { + useEffect(() => { loadSourceConfiguration(); + }, [loadSourceConfiguration]); + + useEffect(() => { fetchEntries(); - }); + }, [fetchEntries]); // Pagination handler const handlePagination = useCallback( diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/bottom_drawer.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/bottom_drawer.tsx index 7c6e58125b48b..5c6e124914f39 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/bottom_drawer.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/bottom_drawer.tsx @@ -38,7 +38,11 @@ export const BottomDrawer: React.FC<{ - + {isOpen ? hideHistory : showHistory} diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx index 76512b8a366c5..92aa015113b2a 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx @@ -16,7 +16,7 @@ import { PageContent } from '../../../../components/page'; import { useSnapshot } from '../hooks/use_snaphot'; import { useWaffleTimeContext } from '../hooks/use_waffle_time'; import { useWaffleFiltersContext } from '../hooks/use_waffle_filters'; -import { useWaffleOptionsContext } from '../hooks/use_waffle_options'; +import { DEFAULT_LEGEND, useWaffleOptionsContext } from '../hooks/use_waffle_options'; import { useSourceContext } from '../../../../containers/source'; import { InfraFormatterType } from '../../../../lib/lib'; import { euiStyled } from '../../../../../../observability/public'; @@ -62,10 +62,14 @@ export const Layout = () => { false ); + const legendPalette = legend?.palette ?? DEFAULT_LEGEND.palette; + const legendSteps = legend?.steps ?? DEFAULT_LEGEND.steps; + const legendReverseColors = legend?.reverseColors ?? DEFAULT_LEGEND.reverseColors; + const options = { formatter: InfraFormatterType.percent, formatTemplate: '{{value}}', - legend: createLegend(legend.palette, legend.steps, legend.reverseColors), + legend: createLegend(legendPalette, legendSteps, legendReverseColors), metric, sort, fields: source?.configuration?.fields, diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx index dd0060f773b49..af712c0611577 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx @@ -4,11 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiTabbedContent } from '@elastic/eui'; +import { EuiPortal, EuiTabs, EuiTab, EuiPanel, EuiTitle } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { EuiPanel } from '@elastic/eui'; -import React, { CSSProperties, useMemo } from 'react'; -import { EuiText } from '@elastic/eui'; +import React, { CSSProperties, useMemo, useState } from 'react'; import { EuiFlexGroup, EuiFlexItem, EuiButtonEmpty } from '@elastic/eui'; import { euiStyled } from '../../../../../../../observability/public'; import { InfraWaffleMapNode, InfraWaffleMapOptions } from '../../../../../lib/lib'; @@ -17,6 +15,7 @@ import { MetricsTab } from './tabs/metrics'; import { LogsTab } from './tabs/logs'; import { ProcessesTab } from './tabs/processes'; import { PropertiesTab } from './tabs/properties'; +import { OVERLAY_Y_START, OVERLAY_BOTTOM_MARGIN, OVERLAY_HEADER_SIZE } from './tabs/shared'; interface Props { isOpen: boolean; @@ -48,46 +47,63 @@ export const NodeContextPopover = ({ }); }, [tabConfigs, node, nodeType, currentTime, options]); + const [selectedTab, setSelectedTab] = useState(0); + if (!isOpen) { return null; } return ( - - - - - -

{node.name}

-
-
- - - - - -
-
- -
+ + + + + + +

{node.name}

+
+
+ + + + + +
+ + {tabs.map((tab, i) => ( + setSelectedTab(i)}> + {tab.name} + + ))} + +
+ {tabs[selectedTab].content} +
+
); }; const OverlayHeader = euiStyled.div` border-color: ${(props) => props.theme.eui.euiBorderColor}; border-bottom-width: ${(props) => props.theme.eui.euiBorderWidthThick}; - padding: ${(props) => props.theme.eui.euiSizeS}; padding-bottom: 0; overflow: hidden; + background-color: ${(props) => props.theme.eui.euiColorLightestShade}; + height: ${OVERLAY_HEADER_SIZE}px; +`; + +const OverlayHeaderTitleWrapper = euiStyled(EuiFlexGroup).attrs({ alignItems: 'center' })` + padding: ${(props) => props.theme.eui.paddingSizes.s} ${(props) => + props.theme.eui.paddingSizes.m} 0; `; const panelStyle: CSSProperties = { position: 'absolute', right: 10, - top: -100, + top: OVERLAY_Y_START, width: '50%', - maxWidth: 600, + maxWidth: 730, zIndex: 2, - height: '50vh', + height: `calc(100vh - ${OVERLAY_Y_START + OVERLAY_BOTTOM_MARGIN}px)`, overflow: 'hidden', }; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes.tsx deleted file mode 100644 index 94ba1150c20dd..0000000000000 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes.tsx +++ /dev/null @@ -1,21 +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 React from 'react'; -import { i18n } from '@kbn/i18n'; -import { TabContent, TabProps } from './shared'; - -const TabComponent = (props: TabProps) => { - return Processes Placeholder; -}; - -export const ProcessesTab = { - id: 'processes', - name: i18n.translate('xpack.infra.nodeDetails.tabs.processes', { - defaultMessage: 'Processes', - }), - content: TabComponent, -}; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx new file mode 100644 index 0000000000000..836d491e6210e --- /dev/null +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx @@ -0,0 +1,102 @@ +/* + * 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 React, { useMemo, useState } from 'react'; +import { i18n } from '@kbn/i18n'; +import { EuiSearchBar, EuiSpacer, EuiEmptyPrompt, EuiButton, Query } from '@elastic/eui'; +import { useProcessList } from '../../../../hooks/use_process_list'; +import { TabContent, TabProps } from '../shared'; +import { STATE_NAMES } from './states'; +import { SummaryTable } from './summary_table'; +import { ProcessesTable } from './processes_table'; + +const TabComponent = ({ currentTime, node, nodeType, options }: TabProps) => { + const [searchFilter, setSearchFilter] = useState(EuiSearchBar.Query.MATCH_ALL); + + const hostTerm = useMemo(() => { + const field = + options.fields && Reflect.has(options.fields, nodeType) + ? Reflect.get(options.fields, nodeType) + : nodeType; + return { [field]: node.name }; + }, [options, node, nodeType]); + + const { loading, error, response, makeRequest: reload } = useProcessList( + hostTerm, + 'metricbeat-*', + options.fields!.timestamp, + currentTime + ); + + if (error) { + return ( + + + {i18n.translate('xpack.infra.metrics.nodeDetails.processListError', { + defaultMessage: 'Unable to show process data', + })} + + } + actions={ + + {i18n.translate('xpack.infra.metrics.nodeDetails.processListRetry', { + defaultMessage: 'Try again', + })} + + } + /> + + ); + } + + return ( + + + + setSearchFilter(query ?? EuiSearchBar.Query.MATCH_ALL)} + box={{ + incremental: true, + placeholder: i18n.translate('xpack.infra.metrics.nodeDetails.searchForProcesses', { + defaultMessage: 'Search for processes…', + }), + }} + filters={[ + { + type: 'field_value_selection', + field: 'state', + name: 'State', + operator: 'exact', + multiSelect: false, + options: Object.entries(STATE_NAMES).map(([value, view]: [string, string]) => ({ + value, + view, + })), + }, + ]} + /> + + + + ); +}; + +export const ProcessesTab = { + id: 'processes', + name: i18n.translate('xpack.infra.metrics.nodeDetails.tabs.processes', { + defaultMessage: 'Processes', + }), + content: TabComponent, +}; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/parse_process_list.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/parse_process_list.ts new file mode 100644 index 0000000000000..88584ef2987e1 --- /dev/null +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/parse_process_list.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ProcessListAPIResponse } from '../../../../../../../../common/http_api'; +import { Process } from './types'; + +export const parseProcessList = (processList: ProcessListAPIResponse) => + processList.map((process) => { + const command = process.id; + let mostRecentPoint; + for (let i = process.rows.length - 1; i >= 0; i--) { + const point = process.rows[i]; + if (point && Array.isArray(point.meta) && point.meta?.length) { + mostRecentPoint = point; + break; + } + } + if (!mostRecentPoint) return { command, cpu: null, memory: null, startTime: null, state: null }; + + const { cpu, memory } = mostRecentPoint; + const { system, process: processMeta, user } = (mostRecentPoint.meta as any[])[0]; + const startTime = system.process.cpu.start_time; + const state = system.process.state; + + const timeseries = { + cpu: pickTimeseries(process.rows, 'cpu'), + memory: pickTimeseries(process.rows, 'memory'), + }; + + return { + command, + cpu, + memory, + startTime, + state, + pid: processMeta.pid, + user: user.name, + timeseries, + } as Process; + }); + +const pickTimeseries = (rows: any[], metricID: string) => ({ + rows: rows.map((row) => ({ + timestamp: row.timestamp, + metric_0: row[metricID], + })), + columns: [ + { name: 'timestamp', type: 'date' }, + { name: 'metric_0', type: 'number' }, + ], + id: metricID, +}); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/process_row.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/process_row.tsx new file mode 100644 index 0000000000000..bbf4a25fc49a7 --- /dev/null +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/process_row.tsx @@ -0,0 +1,267 @@ +/* + * 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 React, { useState, useMemo } from 'react'; +import moment from 'moment'; +import { first, last } from 'lodash'; +import { i18n } from '@kbn/i18n'; +import { + EuiTableRow, + EuiTableRowCell, + EuiButtonEmpty, + EuiCode, + EuiDescriptionList, + EuiDescriptionListTitle, + EuiDescriptionListDescription, + EuiFlexGrid, + EuiFlexGroup, + EuiFlexItem, + EuiButton, + EuiSpacer, +} from '@elastic/eui'; +import { Axis, Chart, Settings, Position, TooltipValue, niceTimeFormatter } from '@elastic/charts'; +import { AutoSizer } from '../../../../../../../components/auto_sizer'; +import { createFormatter } from '../../../../../../../../common/formatters'; +import { useUiSetting } from '../../../../../../../../../../../src/plugins/kibana_react/public'; +import { getChartTheme } from '../../../../../metrics_explorer/components/helpers/get_chart_theme'; +import { calculateDomain } from '../../../../../metrics_explorer/components/helpers/calculate_domain'; +import { MetricsExplorerChartType } from '../../../../../metrics_explorer/hooks/use_metrics_explorer_options'; +import { MetricExplorerSeriesChart } from '../../../../../metrics_explorer/components/series_chart'; +import { MetricsExplorerAggregation } from '../../../../../../../../common/http_api'; +import { Color } from '../../../../../../../../common/color_palette'; +import { euiStyled } from '../../../../../../../../../observability/public'; +import { Process } from './types'; + +interface Props { + cells: React.ReactNode[]; + item: Process; +} + +export const ProcessRow = ({ cells, item }: Props) => { + const [isExpanded, setIsExpanded] = useState(false); + + return ( + <> + + + setIsExpanded(!isExpanded)} + /> + + {cells} + + + {isExpanded && ( + + {({ measureRef, bounds: { height = 0 } }) => ( + + + + + +
+ + {i18n.translate( + 'xpack.infra.metrics.nodeDetails.processes.expandedRowLabelCommand', + { + defaultMessage: 'Command', + } + )} + + + {item.command} + +
+
+ {item.apmTrace && ( + + + {i18n.translate( + 'xpack.infra.metrics.nodeDetails.processes.viewTraceInAPM', + { + defaultMessage: 'View trace in APM', + } + )} + + + )} +
+ + + + {i18n.translate( + 'xpack.infra.metrics.nodeDetails.processes.expandedRowLabelPID', + { + defaultMessage: 'PID', + } + )} + + + {item.pid} + + + + + {i18n.translate( + 'xpack.infra.metrics.nodeDetails.processes.expandedRowLabelUser', + { + defaultMessage: 'User', + } + )} + + + {item.user} + + + + {cpuMetricLabel} + + + + + + {memoryMetricLabel} + + + + + +
+
+ )} +
+ )} +
+ + ); +}; + +interface ProcessChartProps { + timeseries: Process['timeseries']['x']; + color: Color; + label: string; +} +const ProcessChart = ({ timeseries, color, label }: ProcessChartProps) => { + const chartMetric = { + color, + aggregation: 'avg' as MetricsExplorerAggregation, + label, + }; + const isDarkMode = useUiSetting('theme:darkMode'); + + const dateFormatter = useMemo(() => { + if (!timeseries) return () => ''; + const firstTimestamp = first(timeseries.rows)?.timestamp; + const lastTimestamp = last(timeseries.rows)?.timestamp; + + if (firstTimestamp == null || lastTimestamp == null) { + return (value: number) => `${value}`; + } + + return niceTimeFormatter([firstTimestamp, lastTimestamp]); + }, [timeseries]); + + const yAxisFormatter = createFormatter('percent'); + + const tooltipProps = { + headerFormatter: (tooltipValue: TooltipValue) => + moment(tooltipValue.value).format('Y-MM-DD HH:mm:ss.SSS'), + }; + + const dataDomain = calculateDomain(timeseries, [chartMetric], false); + const domain = dataDomain + ? { + max: dataDomain.max * 1.1, // add 10% headroom. + min: dataDomain.min, + } + : { max: 0, min: 0 }; + + return ( + + + + + + + + + ); +}; + +export const CodeLine = euiStyled(EuiCode).attrs({ + transparentBackground: true, +})` + text-overflow: ellipsis; + overflow: hidden; + padding: 0 !important; + & code.euiCodeBlock__code { + white-space: nowrap !important; + vertical-align: middle; + } +`; + +const ExpandedCommandLine = euiStyled(EuiCode).attrs({ + transparentBackground: true, +})` + padding: 0 !important; + margin-bottom: ${(props) => props.theme.eui.euiSizeS}; +`; + +const ExpandedRowCell = euiStyled(EuiTableRowCell).attrs({ + textOnly: false, + colSpan: 6, +})<{ commandHeight: number }>` + height: ${(props) => props.commandHeight + 240}px; + padding: 0 ${(props) => props.theme.eui.paddingSizes.m}; + background-color: ${(props) => props.theme.eui.euiColorLightestShade}; +`; + +const ChartContainer = euiStyled.div` + width: 300px; + height: 140px; +`; + +const cpuMetricLabel = i18n.translate( + 'xpack.infra.metrics.nodeDetails.processes.expandedRowLabelCPU', + { + defaultMessage: 'CPU', + } +); + +const memoryMetricLabel = i18n.translate( + 'xpack.infra.metrics.nodeDetails.processes.expandedRowLabelMemory', + { + defaultMessage: 'Memory', + } +); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/processes_table.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/processes_table.tsx new file mode 100644 index 0000000000000..43f3a333fda83 --- /dev/null +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/processes_table.tsx @@ -0,0 +1,288 @@ +/* + * 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 React, { useMemo, useState, useEffect, useCallback } from 'react'; +import { omit } from 'lodash'; +import { i18n } from '@kbn/i18n'; +import { + EuiTable, + EuiTableHeader, + EuiTableBody, + EuiTableHeaderCell, + EuiTableRowCell, + EuiSpacer, + EuiTablePagination, + EuiLoadingChart, + Query, + SortableProperties, + LEFT_ALIGNMENT, + RIGHT_ALIGNMENT, +} from '@elastic/eui'; +import { ProcessListAPIResponse } from '../../../../../../../../common/http_api'; +import { FORMATTERS } from '../../../../../../../../common/formatters'; +import { euiStyled } from '../../../../../../../../../observability/public'; +import { Process } from './types'; +import { ProcessRow, CodeLine } from './process_row'; +import { parseProcessList } from './parse_process_list'; +import { StateBadge } from './state_badge'; +import { STATE_ORDER } from './states'; + +interface TableProps { + processList: ProcessListAPIResponse; + currentTime: number; + isLoading: boolean; + searchFilter: Query; +} + +function useSortableProperties( + sortablePropertyItems: Array<{ + name: string; + getValue: (obj: T) => any; + isAscending: boolean; + }>, + defaultSortProperty: string +) { + const [sortableProperties] = useState>( + new SortableProperties(sortablePropertyItems, defaultSortProperty) + ); + const [sortedColumn, setSortedColumn] = useState( + omit(sortableProperties.getSortedProperty(), 'getValue') + ); + + return { + setSortedColumn: useCallback( + (property) => { + sortableProperties.sortOn(property); + setSortedColumn(omit(sortableProperties.getSortedProperty(), 'getValue')); + }, + [sortableProperties] + ), + sortedColumn, + sortItems: (items: T[]) => sortableProperties.sortItems(items), + }; +} + +export const ProcessesTable = ({ + processList, + currentTime, + isLoading, + searchFilter, +}: TableProps) => { + const [currentPage, setCurrentPage] = useState(0); + const [itemsPerPage, setItemsPerPage] = useState(10); + useEffect(() => setCurrentPage(0), [processList, searchFilter, itemsPerPage]); + + const { sortedColumn, sortItems, setSortedColumn } = useSortableProperties( + [ + { + name: 'state', + getValue: (item: any) => STATE_ORDER.indexOf(item.state), + isAscending: true, + }, + { + name: 'command', + getValue: (item: any) => item.command.toLowerCase(), + isAscending: true, + }, + { + name: 'startTime', + getValue: (item: any) => Date.parse(item.startTime), + isAscending: false, + }, + { + name: 'cpu', + getValue: (item: any) => item.cpu, + isAscending: false, + }, + { + name: 'memory', + getValue: (item: any) => item.memory, + isAscending: false, + }, + ], + 'state' + ); + + const currentItems = useMemo(() => { + const filteredItems = Query.execute(searchFilter, parseProcessList(processList)) as Process[]; + if (!filteredItems.length) return []; + const sortedItems = sortItems(filteredItems); + return sortedItems; + }, [processList, searchFilter, sortItems]); + + const pageCount = useMemo(() => Math.ceil(currentItems.length / itemsPerPage), [ + itemsPerPage, + currentItems, + ]); + + const pageStartIdx = useMemo(() => currentPage * itemsPerPage + (currentPage > 0 ? 1 : 0), [ + currentPage, + itemsPerPage, + ]); + const currentItemsPage = useMemo( + () => currentItems.slice(pageStartIdx, pageStartIdx + itemsPerPage), + [pageStartIdx, currentItems, itemsPerPage] + ); + + if (isLoading) return ; + + return ( + <> + + + + {columns.map((column) => ( + setSortedColumn(column.field) : undefined} + isSorted={sortedColumn.name === column.field} + isSortAscending={sortedColumn.name === column.field && sortedColumn.isAscending} + > + {column.name} + + ))} + + + + + + + + + ); +}; + +const LoadingPlaceholder = () => { + return ( +
+ +
+ ); +}; + +interface TableBodyProps { + items: Process[]; + currentTime: number; +} +const ProcessesTableBody = ({ items, currentTime }: TableBodyProps) => ( + <> + {items.map((item, i) => { + const cells = columns.map((column) => ( + + {column.render ? column.render(item[column.field], currentTime) : item[column.field]} + + )); + return ; + })} + +); + +const StyledTableBody = euiStyled(EuiTableBody)` + & .euiTableCellContent { + padding-top: 0; + padding-bottom: 0; + + } +`; + +const ONE_MINUTE = 60 * 1000; +const ONE_HOUR = ONE_MINUTE * 60; +const RuntimeCell = ({ startTime, currentTime }: { startTime: string; currentTime: number }) => { + const runtimeLength = currentTime - Date.parse(startTime); + let remainingRuntimeMS = runtimeLength; + const runtimeHours = Math.floor(remainingRuntimeMS / ONE_HOUR); + remainingRuntimeMS -= runtimeHours * ONE_HOUR; + const runtimeMinutes = Math.floor(remainingRuntimeMS / ONE_MINUTE); + remainingRuntimeMS -= runtimeMinutes * ONE_MINUTE; + const runtimeSeconds = Math.floor(remainingRuntimeMS / 1000); + remainingRuntimeMS -= runtimeSeconds * 1000; + + const runtimeDisplayHours = runtimeHours ? `${runtimeHours}:` : ''; + const runtimeDisplayMinutes = runtimeMinutes < 10 ? `0${runtimeMinutes}:` : `${runtimeMinutes}:`; + const runtimeDisplaySeconds = runtimeSeconds < 10 ? `0${runtimeSeconds}` : runtimeSeconds; + + return <>{`${runtimeDisplayHours}${runtimeDisplayMinutes}${runtimeDisplaySeconds}`}; +}; + +const columns: Array<{ + field: keyof Process; + name: string; + sortable: boolean; + render?: Function; + width?: string | number; + textOnly?: boolean; + align?: typeof RIGHT_ALIGNMENT | typeof LEFT_ALIGNMENT; +}> = [ + { + field: 'state', + name: i18n.translate('xpack.infra.metrics.nodeDetails.processes.columnLabelState', { + defaultMessage: 'State', + }), + sortable: true, + render: (state: string) => , + width: 84, + textOnly: false, + }, + { + field: 'command', + name: i18n.translate('xpack.infra.metrics.nodeDetails.processes.columnLabelCommand', { + defaultMessage: 'Command', + }), + sortable: true, + width: '40%', + render: (command: string) => {command}, + }, + { + field: 'startTime', + name: i18n.translate('xpack.infra.metrics.nodeDetails.processes.columnLabelTime', { + defaultMessage: 'Time', + }), + align: RIGHT_ALIGNMENT, + sortable: true, + render: (startTime: string, currentTime: number) => ( + + ), + }, + { + field: 'cpu', + name: i18n.translate('xpack.infra.metrics.nodeDetails.processes.columnLabelCPU', { + defaultMessage: 'CPU', + }), + sortable: true, + render: (value: number) => FORMATTERS.percent(value), + }, + { + field: 'memory', + name: i18n.translate('xpack.infra.metrics.nodeDetails.processes.columnLabelMemory', { + defaultMessage: 'Mem.', + }), + sortable: true, + render: (value: number) => FORMATTERS.percent(value), + }, +]; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/state_badge.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/state_badge.tsx new file mode 100644 index 0000000000000..17306abdb60a3 --- /dev/null +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/state_badge.tsx @@ -0,0 +1,28 @@ +/* + * 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 React from 'react'; +import { EuiBadge } from '@elastic/eui'; +import { STATE_NAMES } from './states'; + +export const StateBadge = ({ state }: { state: string }) => { + switch (state) { + case 'running': + return {STATE_NAMES.running}; + case 'sleeping': + return {STATE_NAMES.sleeping}; + case 'dead': + return {STATE_NAMES.dead}; + case 'stopped': + return {STATE_NAMES.stopped}; + case 'idle': + return {STATE_NAMES.idle}; + case 'zombie': + return {STATE_NAMES.zombie}; + default: + return {STATE_NAMES.unknown}; + } +}; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/states.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/states.ts new file mode 100644 index 0000000000000..b5e32420709eb --- /dev/null +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/states.ts @@ -0,0 +1,33 @@ +/* + * 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 { i18n } from '@kbn/i18n'; + +export const STATE_NAMES = { + running: i18n.translate('xpack.infra.metrics.nodeDetails.processes.stateRunning', { + defaultMessage: 'Running', + }), + sleeping: i18n.translate('xpack.infra.metrics.nodeDetails.processes.stateSleeping', { + defaultMessage: 'Sleeping', + }), + dead: i18n.translate('xpack.infra.metrics.nodeDetails.processes.stateDead', { + defaultMessage: 'Dead', + }), + stopped: i18n.translate('xpack.infra.metrics.nodeDetails.processes.stateStopped', { + defaultMessage: 'Stopped', + }), + idle: i18n.translate('xpack.infra.metrics.nodeDetails.processes.stateIdle', { + defaultMessage: 'Idle', + }), + zombie: i18n.translate('xpack.infra.metrics.nodeDetails.processes.stateZombie', { + defaultMessage: 'Zombie', + }), + unknown: i18n.translate('xpack.infra.metrics.nodeDetails.processes.stateUnknown', { + defaultMessage: 'Unknown', + }), +}; + +export const STATE_ORDER = ['running', 'sleeping', 'stopped', 'idle', 'dead', 'zombie', 'unknown']; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/summary_table.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/summary_table.tsx new file mode 100644 index 0000000000000..59becb0bf534d --- /dev/null +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/summary_table.tsx @@ -0,0 +1,81 @@ +/* + * 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 React, { useMemo } from 'react'; +import { mapValues, countBy } from 'lodash'; +import { i18n } from '@kbn/i18n'; +import { EuiBasicTable, EuiLoadingSpinner, EuiBasicTableColumn } from '@elastic/eui'; +import { euiStyled } from '../../../../../../../../../observability/public'; +import { ProcessListAPIResponse } from '../../../../../../../../common/http_api'; +import { parseProcessList } from './parse_process_list'; +import { STATE_NAMES } from './states'; + +interface Props { + processList: ProcessListAPIResponse; + isLoading: boolean; +} + +type SummaryColumn = { + total: number; +} & Record; + +export const SummaryTable = ({ processList, isLoading }: Props) => { + const parsedList = parseProcessList(processList); + const processCount = useMemo( + () => + [ + { + total: isLoading ? -1 : parsedList.length, + ...mapValues(STATE_NAMES, () => (isLoading ? -1 : 0)), + ...(isLoading ? [] : countBy(parsedList, 'state')), + }, + ] as SummaryColumn[], + [parsedList, isLoading] + ); + return ( + + + + ); +}; + +const loadingRenderer = (value: number) => (value === -1 ? : value); + +const columns = [ + { + field: 'total', + name: i18n.translate('xpack.infra.metrics.nodeDetails.processes.headingTotalProcesses', { + defaultMessage: 'Total processes', + }), + width: 125, + render: loadingRenderer, + }, + ...Object.entries(STATE_NAMES).map(([field, name]) => ({ field, name, render: loadingRenderer })), +] as Array>; + +const LoadingSpinner = euiStyled(EuiLoadingSpinner).attrs({ size: 'm' })` + margin-top: 2px; + margin-bottom: 3px; +`; + +const StyleWrapper = euiStyled.div` + & .euiTableHeaderCell { + border-bottom: none; + & .euiTableCellContent { + padding-bottom: 0; + } + & .euiTableCellContent__text { + font-size: ${(props) => props.theme.eui.euiFontSizeS}; + } + } + + & .euiTableRowCell { + border-top: none; + & .euiTableCellContent { + padding-top: 0; + } + } +`; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/types.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/types.ts new file mode 100644 index 0000000000000..d483fe510c944 --- /dev/null +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/types.ts @@ -0,0 +1,22 @@ +/* + * 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 { MetricsExplorerSeries } from '../../../../../../../../common/http_api'; +import { STATE_NAMES } from './states'; + +export interface Process { + command: string; + cpu: number; + memory: number; + startTime: number; + state: keyof typeof STATE_NAMES; + pid: number; + user: string; + timeseries: { + [x: string]: MetricsExplorerSeries; + }; + apmTrace?: string; // Placeholder +} diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/shared.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/shared.tsx index 241ad7104836e..7386fa64aca9c 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/shared.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/shared.tsx @@ -15,6 +15,13 @@ export interface TabProps { nodeType: InventoryItemType; } +export const OVERLAY_Y_START = 266; +export const OVERLAY_BOTTOM_MARGIN = 16; +export const OVERLAY_HEADER_SIZE = 96; +const contentHeightOffset = OVERLAY_Y_START + OVERLAY_BOTTOM_MARGIN + OVERLAY_HEADER_SIZE; export const TabContent = euiStyled.div` - padding: ${(props) => props.theme.eui.paddingSizes.l}; + padding: ${(props) => props.theme.eui.paddingSizes.s}; + height: calc(100vh - ${contentHeightOffset}px); + overflow-y: auto; + overflow-x: hidden; `; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend.tsx index c211de8fd3d21..ea7bb66e689d9 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend.tsx @@ -17,7 +17,11 @@ import { import { GradientLegend } from './gradient_legend'; import { LegendControls } from './legend_controls'; import { StepLegend } from './steps_legend'; -import { useWaffleOptionsContext, WaffleLegendOptions } from '../../hooks/use_waffle_options'; +import { + DEFAULT_LEGEND, + useWaffleOptionsContext, + WaffleLegendOptions, +} from '../../hooks/use_waffle_options'; import { SteppedGradientLegend } from './stepped_gradient_legend'; interface Props { legend: InfraWaffleMapLegend; @@ -52,7 +56,7 @@ export const Legend: React.FC = ({ dataBounds, legend, bounds, formatter return ( , + indexPattern: string, + timefield: string, + to: number +) { + const decodeResponse = (response: any) => { + return pipe( + ProcessListAPIResponseRT.decode(response), + fold(throwErrors(createPlainError), identity) + ); + }; + + const timerange = { + field: timefield, + interval: 'modules', + to, + from: to - 15 * 60 * 1000, // 15 minutes + }; + + const { error, loading, response, makeRequest } = useHTTPRequest( + '/api/metrics/process_list', + 'POST', + JSON.stringify({ + hostTerm, + timerange, + indexPattern, + }), + decodeResponse + ); + + useEffect(() => { + makeRequest(); + }, [makeRequest]); + + return { + error, + loading, + response, + makeRequest, + }; +} diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts index 35d069adc939e..ddd5a115b7e91 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts @@ -23,6 +23,12 @@ import { import { useUrlState } from '../../../../utils/use_url_state'; import { InventoryItemType, ItemTypeRT } from '../../../../../common/inventory_models/types'; +export const DEFAULT_LEGEND: WaffleLegendOptions = { + palette: 'cool', + steps: 10, + reverseColors: false, +}; + export const DEFAULT_WAFFLE_OPTIONS_STATE: WaffleOptionsState = { metric: { type: 'cpu' }, groupBy: [], @@ -34,11 +40,7 @@ export const DEFAULT_WAFFLE_OPTIONS_STATE: WaffleOptionsState = { accountId: '', region: '', customMetrics: [], - legend: { - palette: 'cool', - steps: 10, - reverseColors: false, - }, + legend: DEFAULT_LEGEND, source: 'default', sort: { by: 'name', direction: 'desc' }, }; @@ -183,10 +185,9 @@ export const WaffleOptionsStateRT = rt.intersection([ accountId: rt.string, region: rt.string, customMetrics: rt.array(SnapshotCustomMetricInputRT), - legend: WaffleLegendOptionsRT, sort: WaffleSortOptionRT, }), - rt.partial({ source: rt.string }), + rt.partial({ source: rt.string, legend: WaffleLegendOptionsRT }), ]); export type WaffleSortOption = rt.TypeOf; diff --git a/x-pack/plugins/infra/server/infra_server.ts b/x-pack/plugins/infra/server/infra_server.ts index 49fe55e3dee01..2bf5687da7e08 100644 --- a/x-pack/plugins/infra/server/infra_server.ts +++ b/x-pack/plugins/infra/server/infra_server.ts @@ -41,6 +41,7 @@ import { initLogSourceConfigurationRoutes, initLogSourceStatusRoutes } from './r import { initSourceRoute } from './routes/source'; import { initAlertPreviewRoute } from './routes/alerting'; import { initGetLogAlertsChartPreviewDataRoute } from './routes/log_alerts'; +import { initProcessListRoute } from './routes/process_list'; export const initInfraServer = (libs: InfraBackendLibs) => { const schema = makeExecutableSchema({ @@ -82,4 +83,5 @@ export const initInfraServer = (libs: InfraBackendLibs) => { initLogSourceStatusRoutes(libs); initAlertPreviewRoute(libs); initGetLogAlertsChartPreviewDataRoute(libs); + initProcessListRoute(libs); }; diff --git a/x-pack/plugins/infra/server/lib/host_details/process_list.ts b/x-pack/plugins/infra/server/lib/host_details/process_list.ts new file mode 100644 index 0000000000000..99e8b2e8f6ab1 --- /dev/null +++ b/x-pack/plugins/infra/server/lib/host_details/process_list.ts @@ -0,0 +1,64 @@ +/* + * 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 { ProcessListAPIRequest, MetricsAPIRequest } from '../../../common/http_api'; +import { getAllMetricsData } from '../../utils/get_all_metrics_data'; +import { query } from '../metrics'; +import { ESSearchClient } from '../metrics/types'; + +export const getProcessList = async ( + client: ESSearchClient, + { hostTerm, timerange, indexPattern }: ProcessListAPIRequest +) => { + const queryBody = { + timerange, + modules: ['system.cpu', 'system.memory'], + groupBy: ['system.process.cmdline'], + filters: [{ term: hostTerm }], + indexPattern, + limit: 9, + metrics: [ + { + id: 'cpu', + aggregations: { + cpu: { + avg: { + field: 'system.process.cpu.total.norm.pct', + }, + }, + }, + }, + { + id: 'memory', + aggregations: { + memory: { + avg: { + field: 'system.process.memory.rss.pct', + }, + }, + }, + }, + { + id: 'meta', + aggregations: { + meta: { + top_hits: { + size: 1, + sort: [{ [timerange.field]: { order: 'desc' } }], + _source: [ + 'system.process.cpu.start_time', + 'system.process.state', + 'process.pid', + 'user.name', + ], + }, + }, + }, + }, + ], + } as MetricsAPIRequest; + return await getAllMetricsData((body: MetricsAPIRequest) => query(client, body), queryBody); +}; diff --git a/x-pack/plugins/infra/server/routes/process_list/index.ts b/x-pack/plugins/infra/server/routes/process_list/index.ts new file mode 100644 index 0000000000000..9851613255d8d --- /dev/null +++ b/x-pack/plugins/infra/server/routes/process_list/index.ts @@ -0,0 +1,50 @@ +/* + * 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 Boom from '@hapi/boom'; +import { pipe } from 'fp-ts/lib/pipeable'; +import { fold } from 'fp-ts/lib/Either'; +import { identity } from 'fp-ts/lib/function'; +import { schema } from '@kbn/config-schema'; +import { InfraBackendLibs } from '../../lib/infra_types'; +import { throwErrors } from '../../../common/runtime_types'; +import { createSearchClient } from '../../lib/create_search_client'; +import { getProcessList } from '../../lib/host_details/process_list'; +import { ProcessListAPIRequestRT, ProcessListAPIResponseRT } from '../../../common/http_api'; + +const escapeHatch = schema.object({}, { unknowns: 'allow' }); + +export const initProcessListRoute = (libs: InfraBackendLibs) => { + const { framework } = libs; + framework.registerRoute( + { + method: 'post', + path: '/api/metrics/process_list', + validate: { + body: escapeHatch, + }, + }, + async (requestContext, request, response) => { + try { + const options = pipe( + ProcessListAPIRequestRT.decode(request.body), + fold(throwErrors(Boom.badRequest), identity) + ); + + const client = createSearchClient(requestContext, framework); + const processListResponse = await getProcessList(client, options); + + return response.ok({ + body: ProcessListAPIResponseRT.encode(processListResponse), + }); + } catch (error) { + return response.internalError({ + body: error.message, + }); + } + } + ); +}; diff --git a/x-pack/plugins/infra/server/utils/get_all_metrics_data.ts b/x-pack/plugins/infra/server/utils/get_all_metrics_data.ts new file mode 100644 index 0000000000000..cec58494d1b98 --- /dev/null +++ b/x-pack/plugins/infra/server/utils/get_all_metrics_data.ts @@ -0,0 +1,34 @@ +/* + * 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 { MetricsAPIResponse, MetricsAPISeries } from '../../common/http_api/metrics_api'; + +export const getAllMetricsData = async ( + query: (options: Options) => Promise, + options: Options, + previousBuckets: MetricsAPISeries[] = [] +): Promise => { + const response = await query(options); + + // Nothing available, return the previous buckets. + if (response.series.length === 0) { + return previousBuckets; + } + + const currentBuckets = response.series; + + // if there are no currentBuckets then we are finished paginating through the results + if (!response.info.afterKey) { + return previousBuckets.concat(currentBuckets); + } + + // There is possibly more data, concat previous and current buckets and call ourselves recursively. + const newOptions = { + ...options, + afterKey: response.info.afterKey, + }; + return getAllMetricsData(query, newOptions, previousBuckets.concat(currentBuckets)); +}; diff --git a/x-pack/plugins/maps/public/classes/sources/es_source/es_source.ts b/x-pack/plugins/maps/public/classes/sources/es_source/es_source.ts index bef0b8c6ea7af..103fd11263330 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_source/es_source.ts +++ b/x-pack/plugins/maps/public/classes/sources/es_source/es_source.ts @@ -134,7 +134,7 @@ export class AbstractESSource extends AbstractVectorSource implements IESSource destroy() { const inspectorAdapters = this.getInspectorAdapters(); - if (inspectorAdapters) { + if (inspectorAdapters?.requests) { inspectorAdapters.requests.resetRequest(this.getId()); } } @@ -164,7 +164,7 @@ export class AbstractESSource extends AbstractVectorSource implements IESSource const inspectorAdapters = this.getInspectorAdapters(); let inspectorRequest: RequestResponder | undefined; - if (inspectorAdapters) { + if (inspectorAdapters?.requests) { inspectorRequest = inspectorAdapters.requests.start(requestName, { id: requestId, description: requestDescription, diff --git a/x-pack/plugins/ml/common/types/ml_url_generator.ts b/x-pack/plugins/ml/common/types/ml_url_generator.ts index b188ac0a87571..9a3d8fc4a4f02 100644 --- a/x-pack/plugins/ml/common/types/ml_url_generator.ts +++ b/x-pack/plugins/ml/common/types/ml_url_generator.ts @@ -132,6 +132,7 @@ export interface TimeSeriesExplorerAppState { forecastId?: string; detectorIndex?: number; entities?: Record; + functionDescription?: string; }; query?: any; } @@ -145,6 +146,7 @@ export interface TimeSeriesExplorerPageState entities?: Record; forecastId?: string; globalState?: MlCommonGlobalState; + functionDescription?: string; } export type TimeSeriesExplorerUrlState = MLPageState< diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/__snapshots__/index.test.tsx.snap b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/__snapshots__/index.test.tsx.snap deleted file mode 100644 index dba73c246c3d0..0000000000000 --- a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/__snapshots__/index.test.tsx.snap +++ /dev/null @@ -1,3 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`AnnotationFlyout Initialization. 1`] = `""`; diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.test.tsx b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.test.tsx index a4d2cd6b091a8..5ad175e2792b7 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.test.tsx +++ b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.test.tsx @@ -5,58 +5,102 @@ */ import useObservable from 'react-use/lib/useObservable'; - import mockAnnotations from '../annotations_table/__mocks__/mock_annotations.json'; - import React from 'react'; -import { mountWithIntl, shallowWithIntl } from '@kbn/test/jest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { IntlProvider } from 'react-intl'; import { Annotation } from '../../../../../common/types/annotations'; -import { annotation$ } from '../../../services/annotations_service'; +import { AnnotationUpdatesService } from '../../../services/annotations_service'; import { AnnotationFlyout } from './index'; +import { MlAnnotationUpdatesContext } from '../../../contexts/ml/ml_annotation_updates_context'; + +jest.mock('../../../util/dependency_cache', () => ({ + getToastNotifications: () => ({ addSuccess: jest.fn(), addDanger: jest.fn() }), +})); + +const MlAnnotationUpdatesContextProvider = ({ + annotationUpdatesService, + children, +}: { + annotationUpdatesService: AnnotationUpdatesService; + children: React.ReactElement; +}) => { + return ( + + {children} + + ); +}; + +const ObservableComponent = (props: any) => { + const { annotationUpdatesService } = props; + const annotationProp = useObservable(annotationUpdatesService!.isAnnotationInitialized$()); + if (annotationProp === undefined) { + return null; + } + return ( + + ); +}; describe('AnnotationFlyout', () => { - test('Initialization.', () => { - const wrapper = shallowWithIntl(); - expect(wrapper).toMatchSnapshot(); + let annotationUpdatesService: AnnotationUpdatesService | null = null; + beforeEach(() => { + annotationUpdatesService = new AnnotationUpdatesService(); }); - test('Update button is disabled with empty annotation', () => { + test('Update button is disabled with empty annotation', async () => { const annotation = mockAnnotations[1] as Annotation; - annotation$.next(annotation); - - // useObservable wraps the observable in a new component - const ObservableComponent = (props: any) => { - const annotationProp = useObservable(annotation$); - if (annotationProp === undefined) { - return null; - } - return ; - }; - - const wrapper = mountWithIntl(); - const updateBtn = wrapper.find('EuiButton').first(); - expect(updateBtn.prop('isDisabled')).toEqual(true); + + annotationUpdatesService!.setValue(annotation); + + const { getByTestId } = render( + + + + ); + const updateBtn = getByTestId('annotationFlyoutUpdateButton'); + expect(updateBtn).toBeDisabled(); }); - test('Error displayed and update button displayed if annotation text is longer than max chars', () => { + test('Error displayed and update button displayed if annotation text is longer than max chars', async () => { const annotation = mockAnnotations[2] as Annotation; - annotation$.next(annotation); - - // useObservable wraps the observable in a new component - const ObservableComponent = (props: any) => { - const annotationProp = useObservable(annotation$); - if (annotationProp === undefined) { - return null; - } - return ; - }; - - const wrapper = mountWithIntl(); - const updateBtn = wrapper.find('EuiButton').first(); - expect(updateBtn.prop('isDisabled')).toEqual(true); - - expect(wrapper.find('EuiFormErrorText')).toHaveLength(1); + annotationUpdatesService!.setValue(annotation); + + const { getByTestId } = render( + + + + ); + const updateBtn = getByTestId('annotationFlyoutUpdateButton'); + expect(updateBtn).toBeDisabled(); + await waitFor(() => { + const errorText = screen.queryByText(/characters above maximum length/); + expect(errorText).not.toBe(undefined); + }); + }); + + test('Flyout disappears when annotation is updated', async () => { + const annotation = mockAnnotations[0] as Annotation; + + annotationUpdatesService!.setValue(annotation); + + const { getByTestId } = render( + + + + ); + const updateBtn = getByTestId('annotationFlyoutUpdateButton'); + expect(updateBtn).not.toBeDisabled(); + expect(screen.queryByTestId('mlAnnotationFlyout')).toBeInTheDocument(); + + await fireEvent.click(updateBtn); + expect(screen.queryByTestId('mlAnnotationFlyout')).not.toBeInTheDocument(); }); }); diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx index 84abe3ed8a821..88996772f49d6 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx +++ b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { Component, FC, ReactNode, useCallback } from 'react'; +import React, { Component, FC, ReactNode, useCallback, useContext } from 'react'; import useObservable from 'react-use/lib/useObservable'; import * as Rx from 'rxjs'; import { cloneDeep } from 'lodash'; @@ -28,15 +28,14 @@ import { import { CommonProps } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { distinctUntilChanged } from 'rxjs/operators'; import { ANNOTATION_MAX_LENGTH_CHARS, ANNOTATION_EVENT_USER, } from '../../../../../common/constants/annotations'; import { - annotation$, annotationsRefreshed, AnnotationState, + AnnotationUpdatesService, } from '../../../services/annotations_service'; import { AnnotationDescriptionList } from '../annotation_description_list'; import { DeleteAnnotationModal } from '../delete_annotation_modal'; @@ -48,6 +47,7 @@ import { } from '../../../../../common/types/annotations'; import { PartitionFieldsType } from '../../../../../common/types/anomalies'; import { PARTITION_FIELDS } from '../../../../../common/constants/anomalies'; +import { MlAnnotationUpdatesContext } from '../../../contexts/ml/ml_annotation_updates_context'; interface ViewableDetector { index: number; @@ -67,6 +67,7 @@ interface Props { }; detectorIndex: number; detectors: ViewableDetector[]; + annotationUpdatesService: AnnotationUpdatesService; } interface State { @@ -85,7 +86,8 @@ export class AnnotationFlyoutUI extends Component { public annotationSub: Rx.Subscription | null = null; componentDidMount() { - this.annotationSub = annotation$.subscribe((v) => { + const { annotationUpdatesService } = this.props; + this.annotationSub = annotationUpdatesService.update$().subscribe((v) => { this.setState({ annotationState: v, }); @@ -100,15 +102,17 @@ export class AnnotationFlyoutUI extends Component { if (this.state.annotationState === null) { return; } + const { annotationUpdatesService } = this.props; - annotation$.next({ + annotationUpdatesService.setValue({ ...this.state.annotationState, annotation: e.target.value, }); }; public cancelEditingHandler = () => { - annotation$.next(null); + const { annotationUpdatesService } = this.props; + annotationUpdatesService.setValue(null); }; public deleteConfirmHandler = () => { @@ -148,7 +152,10 @@ export class AnnotationFlyoutUI extends Component { } this.closeDeleteModal(); - annotation$.next(null); + + const { annotationUpdatesService } = this.props; + + annotationUpdatesService.setValue(null); annotationsRefreshed(); }; @@ -193,7 +200,8 @@ export class AnnotationFlyoutUI extends Component { public saveOrUpdateAnnotation = () => { const { annotationState: originalAnnotation } = this.state; - const { chartDetails, detectorIndex } = this.props; + const { chartDetails, detectorIndex, annotationUpdatesService } = this.props; + if (originalAnnotation === null) { return; } @@ -218,8 +226,7 @@ export class AnnotationFlyoutUI extends Component { } // Mark the annotation created by `user` if and only if annotation is being created, not updated annotation.event = annotation.event ?? ANNOTATION_EVENT_USER; - - annotation$.next(null); + annotationUpdatesService.setValue(null); ml.annotations .indexAnnotation(annotation) @@ -356,16 +363,16 @@ export class AnnotationFlyoutUI extends Component {
- + - + - + {isExistingAnnotation && ( { )} - + {isExistingAnnotation ? ( { } export const AnnotationFlyout: FC = (props) => { - const annotationProp = useObservable( - annotation$.pipe( - distinctUntilChanged((prev, curr) => { - // prevent re-rendering - return prev !== null && curr !== null; - }) - ) - ); + const annotationUpdatesService = useContext(MlAnnotationUpdatesContext); + const annotationProp = useObservable(annotationUpdatesService.isAnnotationInitialized$()); const cancelEditingHandler = useCallback(() => { - annotation$.next(null); + annotationUpdatesService.setValue(null); }, []); if (annotationProp === undefined || annotationProp === null) { @@ -423,7 +429,12 @@ export const AnnotationFlyout: FC = (props) => { const isExistingAnnotation = typeof annotationProp._id !== 'undefined'; return ( - +

@@ -441,7 +452,7 @@ export const AnnotationFlyout: FC = (props) => {

- +
); }; diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/__snapshots__/annotations_table.test.js.snap b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/__snapshots__/annotations_table.test.js.snap index 114a6b235d1ad..0c6fa6669c2eb 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/__snapshots__/annotations_table.test.js.snap +++ b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/__snapshots__/annotations_table.test.js.snap @@ -1,7 +1,7 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`AnnotationsTable Initialization with annotations prop. 1`] = ` - annotation$.next(originalAnnotation ?? annotation)} + onClick={() => annotationUpdatesService.setValue(originalAnnotation ?? annotation)} iconType="pencil" aria-label={editAnnotationsTooltipAriaLabelText} /> @@ -693,4 +694,7 @@ class AnnotationsTableUI extends Component { } } -export const AnnotationsTable = withKibana(AnnotationsTableUI); +export const AnnotationsTable = withKibana((props) => { + const annotationUpdatesService = useContext(MlAnnotationUpdatesContext); + return ; +}); diff --git a/x-pack/plugins/ml/public/application/contexts/ml/ml_annotation_updates_context.ts b/x-pack/plugins/ml/public/application/contexts/ml/ml_annotation_updates_context.ts new file mode 100644 index 0000000000000..37dea3029c8ad --- /dev/null +++ b/x-pack/plugins/ml/public/application/contexts/ml/ml_annotation_updates_context.ts @@ -0,0 +1,14 @@ +/* + * 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 { createContext } from 'react'; +import { AnnotationUpdatesService } from '../../services/annotations_service'; + +export type MlAnnotationUpdatesContextValue = AnnotationUpdatesService; + +export const MlAnnotationUpdatesContext = createContext( + new AnnotationUpdatesService() +); diff --git a/x-pack/plugins/ml/public/application/routing/routes/explorer.tsx b/x-pack/plugins/ml/public/application/routing/routes/explorer.tsx index cb6944e0ecf05..b91a5bd4a1aa4 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/explorer.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/explorer.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { FC, useEffect, useState, useCallback } from 'react'; +import React, { FC, useEffect, useState, useCallback, useMemo } from 'react'; import useObservable from 'react-use/lib/useObservable'; import { i18n } from '@kbn/i18n'; @@ -34,6 +34,8 @@ import { getBreadcrumbWithUrlForApp } from '../breadcrumbs'; import { useTimefilter } from '../../contexts/kibana'; import { isViewBySwimLaneData } from '../../explorer/swimlane_container'; import { JOB_ID } from '../../../../common/constants/anomalies'; +import { MlAnnotationUpdatesContext } from '../../contexts/ml/ml_annotation_updates_context'; +import { AnnotationUpdatesService } from '../../services/annotations_service'; export const explorerRouteFactory = ( navigateToPath: NavigateToPath, @@ -59,10 +61,13 @@ const PageWrapper: FC = ({ deps }) => { jobs: mlJobService.loadJobsWrapper, jobsWithTimeRange: () => ml.jobs.jobsWithTimerange(getDateFormatTz()), }); + const annotationUpdatesService = useMemo(() => new AnnotationUpdatesService(), []); return ( - + + + ); }; diff --git a/x-pack/plugins/ml/public/application/routing/routes/jobs_list.tsx b/x-pack/plugins/ml/public/application/routing/routes/jobs_list.tsx index 2863e59508e35..d91ec27d9a505 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/jobs_list.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/jobs_list.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useEffect, FC } from 'react'; +import React, { useEffect, FC, useMemo } from 'react'; import useObservable from 'react-use/lib/useObservable'; import { i18n } from '@kbn/i18n'; @@ -19,6 +19,8 @@ import { basicResolvers } from '../resolvers'; import { JobsPage } from '../../jobs/jobs_list'; import { useTimefilter } from '../../contexts/kibana'; import { getBreadcrumbWithUrlForApp } from '../breadcrumbs'; +import { AnnotationUpdatesService } from '../../services/annotations_service'; +import { MlAnnotationUpdatesContext } from '../../contexts/ml/ml_annotation_updates_context'; export const jobListRouteFactory = (navigateToPath: NavigateToPath, basePath: string): MlRoute => ({ path: '/jobs', @@ -57,10 +59,13 @@ const PageWrapper: FC = ({ deps }) => { setGlobalState({ refreshInterval }); timefilter.setRefreshInterval(refreshInterval); }, []); + const annotationUpdatesService = useMemo(() => new AnnotationUpdatesService(), []); return ( - + + + ); }; diff --git a/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx b/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx index 9331fdc04b7bb..f0fb4558bcfa9 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx @@ -5,7 +5,7 @@ */ import { isEqual } from 'lodash'; -import React, { FC, useCallback, useEffect, useState } from 'react'; +import React, { FC, useCallback, useEffect, useMemo, useState } from 'react'; import usePrevious from 'react-use/lib/usePrevious'; import moment from 'moment'; @@ -39,7 +39,8 @@ import { basicResolvers } from '../resolvers'; import { getBreadcrumbWithUrlForApp } from '../breadcrumbs'; import { useTimefilter } from '../../contexts/kibana'; import { useToastNotificationService } from '../../services/toast_notification_service'; - +import { AnnotationUpdatesService } from '../../services/annotations_service'; +import { MlAnnotationUpdatesContext } from '../../contexts/ml/ml_annotation_updates_context'; export const timeSeriesExplorerRouteFactory = ( navigateToPath: NavigateToPath, basePath: string @@ -64,13 +65,16 @@ const PageWrapper: FC = ({ deps }) => { jobs: mlJobService.loadJobsWrapper, jobsWithTimeRange: () => ml.jobs.jobsWithTimerange(getDateFormatTz()), }); + const annotationUpdatesService = useMemo(() => new AnnotationUpdatesService(), []); return ( - + + + ); }; @@ -157,6 +161,11 @@ export const TimeSeriesExplorerUrlStateManager: FC ); diff --git a/x-pack/plugins/ml/public/application/services/annotations_service.test.tsx b/x-pack/plugins/ml/public/application/services/annotations_service.test.tsx index 2ba54d243ed1b..969748acc6af8 100644 --- a/x-pack/plugins/ml/public/application/services/annotations_service.test.tsx +++ b/x-pack/plugins/ml/public/application/services/annotations_service.test.tsx @@ -7,20 +7,29 @@ import mockAnnotations from '../components/annotations/annotations_table/__mocks__/mock_annotations.json'; import { Annotation } from '../../../common/types/annotations'; -import { annotation$, annotationsRefresh$, annotationsRefreshed } from './annotations_service'; - +import { + annotationsRefresh$, + annotationsRefreshed, + AnnotationUpdatesService, +} from './annotations_service'; describe('annotations_service', () => { - test('annotation$', () => { + let annotationUpdatesService: AnnotationUpdatesService | null = null; + + beforeEach(() => { + annotationUpdatesService = new AnnotationUpdatesService(); + }); + + test('annotationUpdatesService', () => { const subscriber = jest.fn(); - annotation$.subscribe(subscriber); + annotationUpdatesService!.update$().subscribe(subscriber); // the subscriber should have been triggered with the initial value of null expect(subscriber.mock.calls).toHaveLength(1); expect(subscriber.mock.calls[0][0]).toBe(null); const annotation = mockAnnotations[0] as Annotation; - annotation$.next(annotation); + annotationUpdatesService!.setValue(annotation); // the subscriber should have been triggered with the updated annotation value expect(subscriber.mock.calls).toHaveLength(2); diff --git a/x-pack/plugins/ml/public/application/services/annotations_service.tsx b/x-pack/plugins/ml/public/application/services/annotations_service.tsx index 6493770156cb8..208c3b6ca5827 100644 --- a/x-pack/plugins/ml/public/application/services/annotations_service.tsx +++ b/x-pack/plugins/ml/public/application/services/annotations_service.tsx @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { BehaviorSubject } from 'rxjs'; - +import { BehaviorSubject, Observable } from 'rxjs'; +import { distinctUntilChanged } from 'rxjs/operators'; import { Annotation } from '../../../common/types/annotations'; /* @@ -79,3 +79,25 @@ export const annotation$ = new BehaviorSubject(null); */ export const annotationsRefresh$ = new BehaviorSubject(Date.now()); export const annotationsRefreshed = () => annotationsRefresh$.next(Date.now()); + +export class AnnotationUpdatesService { + private _annotation$: BehaviorSubject = new BehaviorSubject( + null + ); + + public update$() { + return this._annotation$.asObservable(); + } + public isAnnotationInitialized$(): Observable { + return this._annotation$.asObservable().pipe( + distinctUntilChanged((prev, curr) => { + // prevent re-rendering + return prev !== null && curr !== null; + }) + ); + } + + public setValue(annotation: AnnotationState) { + this._annotation$.next(annotation); + } +} diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/plot_function_controls/plot_function_controls.tsx b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/plot_function_controls/plot_function_controls.tsx index 0356c20fecb9a..8e26a912a6051 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/plot_function_controls/plot_function_controls.tsx +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/plot_function_controls/plot_function_controls.tsx @@ -3,9 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; +import React, { useCallback, useEffect } from 'react'; import { EuiFlexItem, EuiFormRow, EuiSelect } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +import { mlJobService } from '../../../services/job_service'; +import { getFunctionDescription, isMetricDetector } from '../../get_function_description'; +import { useToastNotificationService } from '../../../services/toast_notification_service'; +import { ML_JOB_AGGREGATION } from '../../../../../common/constants/aggregation_types'; +import type { CombinedJob } from '../../../../../common/types/anomaly_detection_jobs'; const plotByFunctionOptions = [ { @@ -30,11 +35,70 @@ const plotByFunctionOptions = [ export const PlotByFunctionControls = ({ functionDescription, setFunctionDescription, + selectedDetectorIndex, + selectedJobId, + selectedEntities, }: { functionDescription: undefined | string; setFunctionDescription: (func: string) => void; + selectedDetectorIndex: number; + selectedJobId: string; + selectedEntities: Record; }) => { + const toastNotificationService = useToastNotificationService(); + + const getFunctionDescriptionToPlot = useCallback( + async ( + _selectedDetectorIndex: number, + _selectedEntities: Record, + _selectedJobId: string, + _selectedJob: CombinedJob + ) => { + const functionToPlot = await getFunctionDescription( + { + selectedDetectorIndex: _selectedDetectorIndex, + selectedEntities: _selectedEntities, + selectedJobId: _selectedJobId, + selectedJob: _selectedJob, + }, + toastNotificationService + ); + setFunctionDescription(functionToPlot); + }, + [setFunctionDescription, toastNotificationService] + ); + + useEffect(() => { + if (functionDescription !== undefined) { + return; + } + const selectedJob = mlJobService.getJob(selectedJobId); + if ( + // set if only entity controls are picked + selectedEntities !== undefined && + functionDescription === undefined && + isMetricDetector(selectedJob, selectedDetectorIndex) + ) { + const detector = selectedJob.analysis_config.detectors[selectedDetectorIndex]; + if (detector?.function === ML_JOB_AGGREGATION.METRIC) { + getFunctionDescriptionToPlot( + selectedDetectorIndex, + selectedEntities, + selectedJobId, + selectedJob + ); + } + } + }, [ + setFunctionDescription, + selectedDetectorIndex, + selectedEntities, + selectedJobId, + functionDescription, + ]); + if (functionDescription === undefined) return null; + return ( { +interface TimeseriesChartIntProps { + annotationUpdatesService: AnnotationUpdatesService; + annotationProps: AnnotationState; +} + +declare class TimeseriesChart extends React.Component { focusXScale: d3.scale.Ordinal<{}, number>; } diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js index b2d054becbb1a..6f2beb8fe9067 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js @@ -10,7 +10,7 @@ */ import PropTypes from 'prop-types'; -import React, { Component } from 'react'; +import React, { Component, useContext } from 'react'; import useObservable from 'react-use/lib/useObservable'; import { isEqual, reduce, each, get } from 'lodash'; import d3 from 'd3'; @@ -21,7 +21,6 @@ import { getSeverityWithLow, getMultiBucketImpactLabel, } from '../../../../../common/util/anomaly_utils'; -import { annotation$ } from '../../../services/annotations_service'; import { formatValue } from '../../../formatters/format_value'; import { LINE_CHART_ANOMALY_RADIUS, @@ -51,7 +50,7 @@ import { unhighlightFocusChartAnnotation, ANNOTATION_MIN_WIDTH, } from './timeseries_chart_annotations'; -import { distinctUntilChanged } from 'rxjs/operators'; +import { MlAnnotationUpdatesContext } from '../../../contexts/ml/ml_annotation_updates_context'; const focusZoomPanelHeight = 25; const focusChartHeight = 310; @@ -571,7 +570,6 @@ class TimeseriesChartIntl extends Component { } renderFocusChart() { - console.log('renderFocusChart'); const { focusAggregationInterval, focusAnnotationData: focusAnnotationDataOriginalPropValue, @@ -742,7 +740,8 @@ class TimeseriesChartIntl extends Component { this.focusXScale, showAnnotations, showFocusChartTooltip, - hideFocusChartTooltip + hideFocusChartTooltip, + this.props.annotationUpdatesService ); // disable brushing (creation of annotations) when annotations aren't shown @@ -1800,17 +1799,17 @@ class TimeseriesChartIntl extends Component { } export const TimeseriesChart = (props) => { - const annotationProp = useObservable( - annotation$.pipe( - distinctUntilChanged((prev, curr) => { - // prevent re-rendering - return prev !== null && curr !== null; - }) - ) - ); + const annotationUpdatesService = useContext(MlAnnotationUpdatesContext); + const annotationProp = useObservable(annotationUpdatesService.isAnnotationInitialized$()); if (annotationProp === undefined) { return null; } - return ; + return ( + + ); }; diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts index bd86d07dcd8b7..8757fbad19df3 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts @@ -13,13 +13,14 @@ import { Dictionary } from '../../../../../common/types/common'; import { TimeseriesChart } from './timeseries_chart'; -import { annotation$ } from '../../../services/annotations_service'; +import { AnnotationUpdatesService } from '../../../services/annotations_service'; export const ANNOTATION_MASK_ID = 'mlAnnotationMask'; // getAnnotationBrush() is expected to be called like getAnnotationBrush.call(this) // so it gets passed on the context of the component it gets called from. export function getAnnotationBrush(this: TimeseriesChart) { + const { annotationUpdatesService } = this.props; const focusXScale = this.focusXScale; const annotateBrush = d3.svg.brush().x(focusXScale).on('brushend', brushend.bind(this)); @@ -35,7 +36,7 @@ export function getAnnotationBrush(this: TimeseriesChart) { const endTimestamp = extent[1].getTime(); if (timestamp === endTimestamp) { - annotation$.next(null); + annotationUpdatesService.setValue(null); return; } @@ -47,7 +48,7 @@ export function getAnnotationBrush(this: TimeseriesChart) { type: ANNOTATION_TYPE.ANNOTATION, }; - annotation$.next(annotation); + annotationUpdatesService.setValue(annotation); } return annotateBrush; @@ -105,7 +106,8 @@ export function renderAnnotations( focusXScale: TimeseriesChart['focusXScale'], showAnnotations: boolean, showFocusChartTooltip: (d: Annotation, t: object) => {}, - hideFocusChartTooltip: () => void + hideFocusChartTooltip: () => void, + annotationUpdatesService: AnnotationUpdatesService ) { const upperRectMargin = ANNOTATION_UPPER_RECT_MARGIN; const upperTextMargin = ANNOTATION_UPPER_TEXT_MARGIN; @@ -153,9 +155,9 @@ export function renderAnnotations( // clear a possible existing annotation set up for editing before setting the new one. // this needs to be done explicitly here because a new annotation created using the brush tool // could still be present in the chart. - annotation$.next(null); + annotationUpdatesService.setValue(null); // set the actual annotation and trigger the flyout - annotation$.next(d); + annotationUpdatesService.setValue(d); }); rects diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_with_tooltip.tsx b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_with_tooltip.tsx index 89e7d292dbdf2..23e7740dd048e 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_with_tooltip.tsx +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_with_tooltip.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { FC, useEffect, useState, useCallback } from 'react'; +import React, { FC, useEffect, useState, useCallback, useContext } from 'react'; import { i18n } from '@kbn/i18n'; import { MlTooltipComponent } from '../../../components/chart_tooltip'; import { TimeseriesChart } from './timeseries_chart'; @@ -16,6 +16,7 @@ import { useMlKibana, useNotifications } from '../../../contexts/kibana'; import { getBoundsRoundedToInterval } from '../../../util/time_buckets'; import { ANNOTATION_EVENT_USER } from '../../../../../common/constants/annotations'; import { getControlsForDetector } from '../../get_controls_for_detector'; +import { MlAnnotationUpdatesContext } from '../../../contexts/ml/ml_annotation_updates_context'; interface TimeSeriesChartWithTooltipsProps { bounds: any; @@ -50,6 +51,8 @@ export const TimeSeriesChartWithTooltips: FC = }, } = useMlKibana(); + const annotationUpdatesService = useContext(MlAnnotationUpdatesContext); + const [annotationData, setAnnotationData] = useState([]); const showAnnotationErrorToastNotification = useCallback((error?: string) => { @@ -123,6 +126,7 @@ export const TimeSeriesChartWithTooltips: FC = {(tooltipService) => ( = selectedDetectorIndex) { + const detector = selectedJob.analysis_config.detectors[selectedDetectorIndex]; + if (detector?.function === ML_JOB_AGGREGATION.METRIC) { + return true; + } + } + return false; +} /** * Get the function description from the record with the highest anomaly score @@ -31,11 +43,7 @@ export const getFunctionDescription = async ( ) => { // if the detector's function is metric, fetch the highest scoring anomaly record // and set to plot the function_description (avg/min/max) of that record by default - if ( - selectedJob?.analysis_config?.detectors[selectedDetectorIndex]?.function !== - ML_JOB_AGGREGATION.METRIC - ) - return; + if (!isMetricDetector(selectedJob, selectedDetectorIndex)) return; const entityControls = getControlsForDetector( selectedDetectorIndex, @@ -43,6 +51,7 @@ export const getFunctionDescription = async ( selectedJobId ); const criteriaFields = getCriteriaFields(selectedDetectorIndex, entityControls); + try { const resp = await mlResultsService .getRecordsForCriteria([selectedJob.job_id], criteriaFields, 0, null, null, 1) diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js index f14f11e5d6149..f22cc191ef844 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js @@ -8,7 +8,7 @@ * React component for rendering Single Metric Viewer. */ -import { each, find, get, has, isEqual } from 'lodash'; +import { find, get, has, isEqual } from 'lodash'; import moment from 'moment-timezone'; import { Subject, Subscription, forkJoin } from 'rxjs'; import { map, debounceTime, switchMap, tap, withLatestFrom } from 'rxjs/operators'; @@ -40,7 +40,6 @@ import { isModelPlotEnabled, isModelPlotChartableForDetector, isSourceDataChartableForDetector, - isTimeSeriesViewDetector, mlFunctionToESAggregation, } from '../../../common/util/job_utils'; @@ -84,7 +83,8 @@ import { SeriesControls } from './components/series_controls'; import { TimeSeriesChartWithTooltips } from './components/timeseries_chart/timeseries_chart_with_tooltip'; import { PlotByFunctionControls } from './components/plot_function_controls'; import { aggregationTypeTransform } from '../../../common/util/anomaly_utils'; -import { getFunctionDescription } from './get_function_description'; +import { isMetricDetector } from './get_function_description'; +import { getViewableDetectors } from './timeseriesexplorer_utils/get_viewable_detectors'; // Used to indicate the chart is being plotted across // all partition field values, where the cardinality of the field cannot be @@ -93,20 +93,6 @@ const allValuesLabel = i18n.translate('xpack.ml.timeSeriesExplorer.allPartitionV defaultMessage: 'all', }); -export function getViewableDetectors(selectedJob) { - const jobDetectors = selectedJob.analysis_config.detectors; - const viewableDetectors = []; - each(jobDetectors, (dtr, index) => { - if (isTimeSeriesViewDetector(selectedJob, index)) { - viewableDetectors.push({ - index, - detector_description: dtr.detector_description, - }); - } - }); - return viewableDetectors; -} - function getTimeseriesexplorerDefaultState() { return { chartDetails: undefined, @@ -143,8 +129,6 @@ function getTimeseriesexplorerDefaultState() { zoomTo: undefined, zoomFromFocusLoaded: undefined, zoomToFocusLoaded: undefined, - // Sets function to plot by if original function is metric - functionDescription: undefined, }; } @@ -223,9 +207,7 @@ export class TimeSeriesExplorer extends React.Component { }; setFunctionDescription = (selectedFuction) => { - this.setState({ - functionDescription: selectedFuction, - }); + this.props.appStateHandler(APP_STATE_ACTION.SET_FUNCTION_DESCRIPTION, selectedFuction); }; previousChartProps = {}; @@ -280,9 +262,17 @@ export class TimeSeriesExplorer extends React.Component { * Gets focus data for the current component state/ */ getFocusData(selection) { - const { selectedJobId, selectedForecastId, selectedDetectorIndex } = this.props; - const { modelPlotEnabled, functionDescription } = this.state; + const { + selectedJobId, + selectedForecastId, + selectedDetectorIndex, + functionDescription, + } = this.props; + const { modelPlotEnabled } = this.state; const selectedJob = mlJobService.getJob(selectedJobId); + if (isMetricDetector(selectedJob, selectedDetectorIndex) && functionDescription === undefined) { + return; + } const entityControls = this.getControlsForDetector(); // Calculate the aggregation interval for the focus chart. @@ -333,8 +323,8 @@ export class TimeSeriesExplorer extends React.Component { selectedJobId, tableInterval, tableSeverity, + functionDescription, } = this.props; - const { functionDescription } = this.state; const selectedJob = mlJobService.getJob(selectedJobId); const entityControls = this.getControlsForDetector(); @@ -394,24 +384,6 @@ export class TimeSeriesExplorer extends React.Component { ); }; - getFunctionDescription = async () => { - const { selectedDetectorIndex, selectedEntities, selectedJobId } = this.props; - const selectedJob = mlJobService.getJob(selectedJobId); - - const functionDescriptionToPlot = await getFunctionDescription( - { - selectedDetectorIndex, - selectedEntities, - selectedJobId, - selectedJob, - }, - this.props.toastNotificationService - ); - if (!this.unmounted) { - this.setFunctionDescription(functionDescriptionToPlot); - } - }; - setForecastId = (forecastId) => { this.props.appStateHandler(APP_STATE_ACTION.SET_FORECAST_ID, forecastId); }; @@ -424,14 +396,22 @@ export class TimeSeriesExplorer extends React.Component { selectedForecastId, selectedJobId, zoom, + functionDescription, } = this.props; - const { loadCounter: currentLoadCounter, functionDescription } = this.state; + const { loadCounter: currentLoadCounter } = this.state; const currentSelectedJob = mlJobService.getJob(selectedJobId); if (currentSelectedJob === undefined) { return; } + if ( + isMetricDetector(currentSelectedJob, selectedDetectorIndex) && + functionDescription === undefined + ) { + return; + } + const functionToPlotByIfMetric = aggregationTypeTransform.toES(functionDescription); this.contextChartSelectedInitCallDone = false; @@ -845,7 +825,7 @@ export class TimeSeriesExplorer extends React.Component { this.componentDidUpdate(); } - componentDidUpdate(previousProps, previousState) { + componentDidUpdate(previousProps) { if (previousProps === undefined || previousProps.selectedJobId !== this.props.selectedJobId) { this.contextChartSelectedInitCallDone = false; this.setState({ fullRefresh: false, loading: true }, () => { @@ -853,15 +833,6 @@ export class TimeSeriesExplorer extends React.Component { }); } - if ( - previousProps === undefined || - previousProps.selectedJobId !== this.props.selectedJobId || - previousProps.selectedDetectorIndex !== this.props.selectedDetectorIndex || - !isEqual(previousProps.selectedEntities, this.props.selectedEntities) - ) { - this.getFunctionDescription(); - } - if ( previousProps === undefined || previousProps.selectedForecastId !== this.props.selectedForecastId @@ -885,7 +856,7 @@ export class TimeSeriesExplorer extends React.Component { !isEqual(previousProps.selectedEntities, this.props.selectedEntities) || previousProps.selectedForecastId !== this.props.selectedForecastId || previousProps.selectedJobId !== this.props.selectedJobId || - previousState.functionDescription !== this.state.functionDescription + previousProps.functionDescription !== this.props.functionDescription ) { const fullRefresh = previousProps === undefined || @@ -894,7 +865,7 @@ export class TimeSeriesExplorer extends React.Component { !isEqual(previousProps.selectedEntities, this.props.selectedEntities) || previousProps.selectedForecastId !== this.props.selectedForecastId || previousProps.selectedJobId !== this.props.selectedJobId || - previousState.functionDescription !== this.state.functionDescription; + previousProps.functionDescription !== this.props.functionDescription; this.loadSingleMetricData(fullRefresh); } @@ -965,7 +936,6 @@ export class TimeSeriesExplorer extends React.Component { zoomTo, zoomFromFocusLoaded, zoomToFocusLoaded, - functionDescription, } = this.state; const chartProps = { modelPlotEnabled, @@ -1014,7 +984,6 @@ export class TimeSeriesExplorer extends React.Component { this.previousShowForecast = showForecast; this.previousShowModelBounds = showModelBounds; - console.log('Timeseriesexplorer rerendered'); return ( {fieldNamesWithEmptyValues.length > 0 && ( @@ -1045,15 +1014,13 @@ export class TimeSeriesExplorer extends React.Component { selectedEntities={this.props.selectedEntities} bounds={bounds} > - {functionDescription && ( - - )} + {arePartitioningFieldsProvided && ( diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_constants.ts b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_constants.ts index a801a1c5ce6f5..6cd58f42f929a 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_constants.ts +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_constants.ts @@ -15,6 +15,7 @@ export const APP_STATE_ACTION = { SET_FORECAST_ID: 'SET_FORECAST_ID', SET_ZOOM: 'SET_ZOOM', UNSET_ZOOM: 'UNSET_ZOOM', + SET_FUNCTION_DESCRIPTION: 'SET_FUNCTION_DESCRIPTION', }; export const CHARTS_POINT_TARGET = 500; diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_utils/get_viewable_detectors.ts b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_utils/get_viewable_detectors.ts new file mode 100644 index 0000000000000..25d7751da8277 --- /dev/null +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_utils/get_viewable_detectors.ts @@ -0,0 +1,29 @@ +/* + * 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 { CombinedJob } from '../../../../common/types/anomaly_detection_jobs'; +import { isTimeSeriesViewDetector } from '../../../../common/util/job_utils'; + +interface ViewableDetector { + index: number; + detector_description: string | undefined; + function: string; +} +export function getViewableDetectors(selectedJob: CombinedJob): ViewableDetector[] { + const jobDetectors = selectedJob.analysis_config.detectors; + const viewableDetectors: ViewableDetector[] = []; + jobDetectors.forEach((dtr, index) => { + if (isTimeSeriesViewDetector(selectedJob, index)) { + viewableDetectors.push({ + index, + detector_description: dtr.detector_description, + function: dtr.function, + }); + } + }); + + return viewableDetectors; +} diff --git a/x-pack/plugins/ml/public/ml_url_generator/anomaly_detection_urls_generator.ts b/x-pack/plugins/ml/public/ml_url_generator/anomaly_detection_urls_generator.ts index 6d7e286a29476..d53dfa8fd19c9 100644 --- a/x-pack/plugins/ml/public/ml_url_generator/anomaly_detection_urls_generator.ts +++ b/x-pack/plugins/ml/public/ml_url_generator/anomaly_detection_urls_generator.ts @@ -163,6 +163,7 @@ export function createSingleMetricViewerUrl( forecastId, entities, globalState, + functionDescription, } = params; let queryState: Partial = {}; @@ -189,6 +190,10 @@ export function createSingleMetricViewerUrl( if (entities !== undefined) { mlTimeSeriesExplorer.entities = entities; } + if (functionDescription !== undefined) { + mlTimeSeriesExplorer.functionDescription = functionDescription; + } + appState.mlTimeSeriesExplorer = mlTimeSeriesExplorer; if (zoom) appState.zoom = zoom; diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_settings_collector.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_settings_collector.ts index 0dd5ce291f972..2b81f1078ad0a 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_settings_collector.ts +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_settings_collector.ts @@ -44,15 +44,23 @@ interface EmailSettingData { xpack: { default_admin_email: string | null }; } -export interface KibanaSettingsCollector extends Collector { +export interface KibanaSettingsCollectorExtraOptions { getEmailValueStructure(email: string | null): EmailSettingData; } +export type KibanaSettingsCollector = Collector & + KibanaSettingsCollectorExtraOptions; + export function getSettingsCollector( usageCollection: UsageCollectionSetup, config: MonitoringConfig ) { - return usageCollection.makeStatsCollector({ + return usageCollection.makeStatsCollector< + EmailSettingData | undefined, + unknown, + false, + KibanaSettingsCollectorExtraOptions + >({ type: KIBANA_SETTINGS_TYPE, isReady: () => true, schema: { @@ -60,7 +68,7 @@ export function getSettingsCollector( default_admin_email: { type: 'text' }, }, }, - async fetch(this: KibanaSettingsCollector) { + async fetch() { let kibanaSettingsData; const defaultAdminEmail = await checkForEmailValue(config); diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.test.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.test.ts index 2f63a878b0cde..8a2283420ac95 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.test.ts +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.test.ts @@ -6,6 +6,7 @@ import { getMonitoringUsageCollector } from './get_usage_collector'; import { fetchClusters } from '../../lib/alerts/fetch_clusters'; +import { elasticsearchServiceMock } from '../../../../../../src/core/server/mocks'; jest.mock('../../lib/alerts/fetch_clusters', () => ({ fetchClusters: jest.fn().mockImplementation(() => { @@ -57,7 +58,7 @@ jest.mock('./lib/fetch_license_type', () => ({ })); describe('getMonitoringUsageCollector', () => { - const callCluster = jest.fn(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); const config: any = { ui: { ccs: { @@ -70,7 +71,7 @@ describe('getMonitoringUsageCollector', () => { const usageCollection: any = { makeUsageCollector: jest.fn(), }; - await getMonitoringUsageCollector(usageCollection, config, callCluster); + await getMonitoringUsageCollector(usageCollection, config, esClient); const mock = (usageCollection.makeUsageCollector as jest.Mock).mock; @@ -120,11 +121,11 @@ describe('getMonitoringUsageCollector', () => { makeUsageCollector: jest.fn(), }; - await getMonitoringUsageCollector(usageCollection, config, callCluster); + await getMonitoringUsageCollector(usageCollection, config, esClient); const mock = (usageCollection.makeUsageCollector as jest.Mock).mock; const args = mock.calls[0]; - const result = await args[0].fetch(); + const result = await args[0].fetch({}); expect(result).toStrictEqual({ hasMonitoringData: true, clusters: [ @@ -147,7 +148,7 @@ describe('getMonitoringUsageCollector', () => { makeUsageCollector: jest.fn(), }; - await getMonitoringUsageCollector(usageCollection, config, callCluster); + await getMonitoringUsageCollector(usageCollection, config, esClient); const mock = (usageCollection.makeUsageCollector as jest.Mock).mock; const args = mock.calls[0]; @@ -155,7 +156,27 @@ describe('getMonitoringUsageCollector', () => { return []; }); - const result = await args[0].fetch(); + const result = await args[0].fetch({}); + expect(result).toStrictEqual({ + hasMonitoringData: false, + clusters: [], + }); + }); + + it('should handle scoped data', async () => { + const usageCollection: any = { + makeUsageCollector: jest.fn(), + }; + + await getMonitoringUsageCollector(usageCollection, config, esClient); + const mock = (usageCollection.makeUsageCollector as jest.Mock).mock; + const args = mock.calls[0]; + + (fetchClusters as jest.Mock).mockImplementation(() => { + return []; + }); + + const result = await args[0].fetch({ kibanaRequest: {} }); expect(result).toStrictEqual({ hasMonitoringData: false, clusters: [], diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.ts index 278a6c163c0ad..038042f109817 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.ts +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.ts @@ -5,7 +5,7 @@ */ import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; -import { LegacyAPICaller } from 'src/core/server'; +import { ILegacyClusterClient } from 'src/core/server'; import { MonitoringConfig } from '../../config'; import { fetchAvailableCcs } from '../../lib/alerts/fetch_available_ccs'; import { getStackProductsUsage } from './lib/get_stack_products_usage'; @@ -18,9 +18,9 @@ import { fetchClusters } from '../../lib/alerts/fetch_clusters'; export function getMonitoringUsageCollector( usageCollection: UsageCollectionSetup, config: MonitoringConfig, - callCluster: LegacyAPICaller + legacyEsClient: ILegacyClusterClient ) { - return usageCollection.makeUsageCollector({ + return usageCollection.makeUsageCollector({ type: 'monitoring', isReady: () => true, schema: { @@ -97,7 +97,13 @@ export function getMonitoringUsageCollector( }, }, }, - fetch: async () => { + extendFetchContext: { + kibanaRequest: true, + }, + fetch: async ({ kibanaRequest }) => { + const callCluster = kibanaRequest + ? legacyEsClient.asScoped(kibanaRequest).callAsCurrentUser + : legacyEsClient.callAsInternalUser; const usageClusters: MonitoringClusterStackProductUsage[] = []; const availableCcs = config.ui.ccs.enabled ? await fetchAvailableCcs(callCluster) : []; const elasticsearchIndex = getCcsIndexPattern(INDEX_PATTERN_ELASTICSEARCH, availableCcs); diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/index.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/index.ts index 47ad78b29962c..25e243656898c 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/index.ts +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/index.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { LegacyAPICaller } from 'src/core/server'; +import { ILegacyClusterClient } from 'src/core/server'; import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; import { getSettingsCollector } from './get_settings_collector'; import { getMonitoringUsageCollector } from './get_usage_collector'; @@ -15,10 +15,10 @@ export { KibanaSettingsCollector } from './get_settings_collector'; export function registerCollectors( usageCollection: UsageCollectionSetup, config: MonitoringConfig, - callCluster: LegacyAPICaller + legacyEsClient: ILegacyClusterClient ) { usageCollection.registerCollector(getSettingsCollector(usageCollection, config)); usageCollection.registerCollector( - getMonitoringUsageCollector(usageCollection, config, callCluster) + getMonitoringUsageCollector(usageCollection, config, legacyEsClient) ); } diff --git a/x-pack/plugins/monitoring/server/plugin.ts b/x-pack/plugins/monitoring/server/plugin.ts index d3e5028d72fcc..41b501d88af99 100644 --- a/x-pack/plugins/monitoring/server/plugin.ts +++ b/x-pack/plugins/monitoring/server/plugin.ts @@ -173,7 +173,7 @@ export class Plugin { }, }); - registerCollectors(plugins.usageCollection, config, cluster.callAsInternalUser); + registerCollectors(plugins.usageCollection, config, cluster); } // Always create the bulk uploader diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_all_stats.test.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_all_stats.test.ts index 099f6915611cb..a119686afe663 100644 --- a/x-pack/plugins/monitoring/server/telemetry_collection/get_all_stats.test.ts +++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_all_stats.test.ts @@ -180,6 +180,7 @@ describe('get_all_stats', () => { esClient: esClient as any, soClient: soClient as any, usageCollection: {} as any, + kibanaRequest: undefined, timestamp, }, { @@ -206,6 +207,7 @@ describe('get_all_stats', () => { esClient: esClient as any, soClient: soClient as any, usageCollection: {} as any, + kibanaRequest: undefined, timestamp, }, { diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_cluster_uuids.test.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_cluster_uuids.test.ts index 0acdb9968bc03..b296ff090aedd 100644 --- a/x-pack/plugins/monitoring/server/telemetry_collection/get_cluster_uuids.test.ts +++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_cluster_uuids.test.ts @@ -13,6 +13,7 @@ import { } from './get_cluster_uuids'; describe('get_cluster_uuids', () => { + const kibanaRequest = undefined; const callCluster = sinon.stub(); const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser; const soClient = savedObjectsRepositoryMock.create(); @@ -33,7 +34,7 @@ describe('get_cluster_uuids', () => { callCluster.withArgs('search').returns(Promise.resolve(response)); expect( await getClusterUuids( - { callCluster, esClient, soClient, timestamp, usageCollection: {} as any }, + { callCluster, esClient, soClient, timestamp, kibanaRequest, usageCollection: {} as any }, { maxBucketSize: 1, } as any @@ -47,7 +48,7 @@ describe('get_cluster_uuids', () => { callCluster.returns(Promise.resolve(response)); expect( await fetchClusterUuids( - { callCluster, esClient, soClient, timestamp, usageCollection: {} as any }, + { callCluster, esClient, soClient, timestamp, kibanaRequest, usageCollection: {} as any }, { maxBucketSize: 1, } as any diff --git a/x-pack/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts b/x-pack/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts index 500185cd7e14f..5a1cdfe867590 100644 --- a/x-pack/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts +++ b/x-pack/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts @@ -333,13 +333,32 @@ export class HeadlessChromiumDriver { private _shouldUseCustomHeaders(conditions: ConditionalHeadersConditions, url: string) { const { hostname, protocol, port, pathname } = parseUrl(url); - if (port === null) throw new Error(`URL missing port: ${url}`); + // `port` is null in URLs that don't explicitly state it, + // however we can derive the port from the protocol (http/https) + // IE: https://feeds-staging.elastic.co/kibana/v8.0.0.json + const derivedPort = (() => { + if (port) { + return port; + } + + if (protocol === 'http:') { + return '80'; + } + + if (protocol === 'https:') { + return '443'; + } + + return null; + })(); + + if (derivedPort === null) throw new Error(`URL missing port: ${url}`); if (pathname === null) throw new Error(`URL missing pathname: ${url}`); return ( hostname === conditions.hostname && protocol === `${conditions.protocol}:` && - this._shouldUseCustomHeadersForPort(conditions, port) && + this._shouldUseCustomHeadersForPort(conditions, derivedPort) && pathname.startsWith(`${conditions.basePath}/`) ); } diff --git a/x-pack/plugins/reporting/server/usage/reporting_usage_collector.test.ts b/x-pack/plugins/reporting/server/usage/reporting_usage_collector.test.ts index 4cecc2e24867f..fff18353c58b0 100644 --- a/x-pack/plugins/reporting/server/usage/reporting_usage_collector.test.ts +++ b/x-pack/plugins/reporting/server/usage/reporting_usage_collector.test.ts @@ -74,7 +74,7 @@ describe('license checks', () => { let usageStats: any; beforeAll(async () => { const plugins = getPluginsMock({ license: 'basic' }); - const { fetch } = getReportingUsageCollector( + const collector = getReportingUsageCollector( mockCore, plugins.usageCollection, getLicenseMock('basic'), @@ -83,7 +83,7 @@ describe('license checks', () => { return Promise.resolve(true); } ); - usageStats = await fetch(getMockFetchClients(getResponseMock())); + usageStats = await collector.fetch(getMockFetchClients(getResponseMock())); }); test('sets enables to true', async () => { @@ -103,7 +103,7 @@ describe('license checks', () => { let usageStats: any; beforeAll(async () => { const plugins = getPluginsMock({ license: 'none' }); - const { fetch } = getReportingUsageCollector( + const collector = getReportingUsageCollector( mockCore, plugins.usageCollection, getLicenseMock('none'), @@ -112,7 +112,7 @@ describe('license checks', () => { return Promise.resolve(true); } ); - usageStats = await fetch(getMockFetchClients(getResponseMock())); + usageStats = await collector.fetch(getMockFetchClients(getResponseMock())); }); test('sets enables to true', async () => { @@ -132,7 +132,7 @@ describe('license checks', () => { let usageStats: any; beforeAll(async () => { const plugins = getPluginsMock({ license: 'platinum' }); - const { fetch } = getReportingUsageCollector( + const collector = getReportingUsageCollector( mockCore, plugins.usageCollection, getLicenseMock('platinum'), @@ -141,7 +141,7 @@ describe('license checks', () => { return Promise.resolve(true); } ); - usageStats = await fetch(getMockFetchClients(getResponseMock())); + usageStats = await collector.fetch(getMockFetchClients(getResponseMock())); }); test('sets enables to true', async () => { @@ -161,7 +161,7 @@ describe('license checks', () => { let usageStats: any; beforeAll(async () => { const plugins = getPluginsMock({ license: 'basic' }); - const { fetch } = getReportingUsageCollector( + const collector = getReportingUsageCollector( mockCore, plugins.usageCollection, getLicenseMock('basic'), @@ -170,7 +170,7 @@ describe('license checks', () => { return Promise.resolve(true); } ); - usageStats = await fetch(getMockFetchClients({})); + usageStats = await collector.fetch(getMockFetchClients({})); }); test('sets enables to true', async () => { @@ -193,7 +193,7 @@ describe('data modeling', () => { }); test('with normal looking usage data', async () => { const plugins = getPluginsMock(); - const { fetch } = getReportingUsageCollector( + const collector = getReportingUsageCollector( mockCore, plugins.usageCollection, getLicenseMock(), @@ -237,13 +237,13 @@ describe('data modeling', () => { }, } as SearchResponse) // prettier-ignore ); - const usageStats = await fetch(collectorFetchContext); + const usageStats = await collector.fetch(collectorFetchContext); expect(usageStats).toMatchSnapshot(); }); test('with sparse data', async () => { const plugins = getPluginsMock(); - const { fetch } = getReportingUsageCollector( + const collector = getReportingUsageCollector( mockCore, plugins.usageCollection, getLicenseMock(), @@ -287,13 +287,13 @@ describe('data modeling', () => { }, } as SearchResponse) // prettier-ignore ); - const usageStats = await fetch(collectorFetchContext); + const usageStats = await collector.fetch(collectorFetchContext); expect(usageStats).toMatchSnapshot(); }); test('with empty data', async () => { const plugins = getPluginsMock(); - const { fetch } = getReportingUsageCollector( + const collector = getReportingUsageCollector( mockCore, plugins.usageCollection, getLicenseMock(), @@ -337,7 +337,7 @@ describe('data modeling', () => { }, } as SearchResponse) // prettier-ignore ); - const usageStats = await fetch(collectorFetchContext); + const usageStats = await collector.fetch(collectorFetchContext); expect(usageStats).toMatchSnapshot(); }); diff --git a/x-pack/plugins/rollup/server/lib/search_strategies/register_rollup_search_strategy.test.js b/x-pack/plugins/rollup/server/lib/search_strategies/register_rollup_search_strategy.test.js deleted file mode 100644 index 8672a8b8f6849..0000000000000 --- a/x-pack/plugins/rollup/server/lib/search_strategies/register_rollup_search_strategy.test.js +++ /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 { registerRollupSearchStrategy } from './register_rollup_search_strategy'; - -describe('Register Rollup Search Strategy', () => { - let addSearchStrategy; - let getRollupService; - - beforeEach(() => { - addSearchStrategy = jest.fn().mockName('addSearchStrategy'); - getRollupService = jest.fn().mockName('getRollupService'); - }); - - test('should run initialization', () => { - registerRollupSearchStrategy(addSearchStrategy, getRollupService); - - expect(addSearchStrategy).toHaveBeenCalled(); - }); -}); diff --git a/x-pack/plugins/rollup/server/lib/search_strategies/register_rollup_search_strategy.ts b/x-pack/plugins/rollup/server/lib/search_strategies/register_rollup_search_strategy.ts deleted file mode 100644 index 22dafbb71d802..0000000000000 --- a/x-pack/plugins/rollup/server/lib/search_strategies/register_rollup_search_strategy.ts +++ /dev/null @@ -1,28 +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 { ILegacyScopedClusterClient } from 'src/core/server'; -import { - DefaultSearchCapabilities, - AbstractSearchStrategy, - ReqFacade, -} from '../../../../../../src/plugins/vis_type_timeseries/server'; -import { getRollupSearchStrategy } from './rollup_search_strategy'; -import { getRollupSearchCapabilities } from './rollup_search_capabilities'; - -export const registerRollupSearchStrategy = ( - addSearchStrategy: (searchStrategy: any) => void, - getRollupService: (reg: ReqFacade) => Promise -) => { - const RollupSearchCapabilities = getRollupSearchCapabilities(DefaultSearchCapabilities); - const RollupSearchStrategy = getRollupSearchStrategy( - AbstractSearchStrategy, - RollupSearchCapabilities, - getRollupService - ); - - addSearchStrategy(new RollupSearchStrategy()); -}; diff --git a/x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_capabilities.ts b/x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_capabilities.ts deleted file mode 100644 index 354bf641114c7..0000000000000 --- a/x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_capabilities.ts +++ /dev/null @@ -1,115 +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, has } from 'lodash'; -import { KibanaRequest } from 'src/core/server'; -import { leastCommonInterval, isCalendarInterval } from './lib/interval_helper'; - -export const getRollupSearchCapabilities = (DefaultSearchCapabilities: any) => - class RollupSearchCapabilities extends DefaultSearchCapabilities { - constructor( - req: KibanaRequest, - fieldsCapabilities: { [key: string]: any }, - rollupIndex: string - ) { - super(req, fieldsCapabilities); - - this.rollupIndex = rollupIndex; - this.availableMetrics = get(fieldsCapabilities, `${rollupIndex}.aggs`, {}); - } - - public get dateHistogram() { - const [dateHistogram] = Object.values(this.availableMetrics.date_histogram); - - return dateHistogram; - } - - public get defaultTimeInterval() { - return ( - this.dateHistogram.fixed_interval || - this.dateHistogram.calendar_interval || - /* - Deprecation: [interval] on [date_histogram] is deprecated, use [fixed_interval] or [calendar_interval] in the future. - We can remove the following line only for versions > 8.x - */ - this.dateHistogram.interval || - null - ); - } - - public get searchTimezone() { - return get(this.dateHistogram, 'time_zone', null); - } - - public get whiteListedMetrics() { - const baseRestrictions = this.createUiRestriction({ - count: this.createUiRestriction(), - }); - - const getFields = (fields: { [key: string]: any }) => - Object.keys(fields).reduce( - (acc, item) => ({ - ...acc, - [item]: true, - }), - this.createUiRestriction({}) - ); - - return Object.keys(this.availableMetrics).reduce( - (acc, item) => ({ - ...acc, - [item]: getFields(this.availableMetrics[item]), - }), - baseRestrictions - ); - } - - public get whiteListedGroupByFields() { - return this.createUiRestriction({ - everything: true, - terms: has(this.availableMetrics, 'terms'), - }); - } - - public get whiteListedTimerangeModes() { - return this.createUiRestriction({ - last_value: true, - }); - } - - getValidTimeInterval(userIntervalString: string) { - const parsedRollupJobInterval = this.parseInterval(this.defaultTimeInterval); - const inRollupJobUnit = this.convertIntervalToUnit( - userIntervalString, - parsedRollupJobInterval.unit - ); - - const getValidCalendarInterval = () => { - let unit = parsedRollupJobInterval.unit; - - if (inRollupJobUnit.value > parsedRollupJobInterval.value) { - const inSeconds = this.convertIntervalToUnit(userIntervalString, 's'); - - unit = this.getSuitableUnit(inSeconds.value); - } - - return { - value: 1, - unit, - }; - }; - - const getValidFixedInterval = () => ({ - value: leastCommonInterval(inRollupJobUnit.value, parsedRollupJobInterval.value), - unit: parsedRollupJobInterval.unit, - }); - - const { value, unit } = (isCalendarInterval(parsedRollupJobInterval) - ? getValidCalendarInterval - : getValidFixedInterval)(); - - return `${value}${unit}`; - } - }; diff --git a/x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_strategy.ts b/x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_strategy.ts deleted file mode 100644 index dcf6629d35397..0000000000000 --- a/x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_strategy.ts +++ /dev/null @@ -1,94 +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 { keyBy, isString } from 'lodash'; -import { ILegacyScopedClusterClient } from 'src/core/server'; -import { ReqFacade } from '../../../../../../src/plugins/vis_type_timeseries/server'; - -import { - mergeCapabilitiesWithFields, - getCapabilitiesForRollupIndices, -} from '../../../../../../src/plugins/data/server'; - -const getRollupIndices = (rollupData: { [key: string]: any }) => Object.keys(rollupData); - -const isIndexPatternContainsWildcard = (indexPattern: string) => indexPattern.includes('*'); -const isIndexPatternValid = (indexPattern: string) => - indexPattern && isString(indexPattern) && !isIndexPatternContainsWildcard(indexPattern); - -export const getRollupSearchStrategy = ( - AbstractSearchStrategy: any, - RollupSearchCapabilities: any, - getRollupService: (reg: ReqFacade) => Promise -) => - class RollupSearchStrategy extends AbstractSearchStrategy { - name = 'rollup'; - - constructor() { - super('rollup', { rest_total_hits_as_int: true }); - } - - async search(req: ReqFacade, bodies: any[], options = {}) { - const rollupService = await getRollupService(req); - const requests: any[] = []; - bodies.forEach((body) => { - requests.push( - rollupService.callAsCurrentUser('rollup.search', { - ...body, - rest_total_hits_as_int: true, - }) - ); - }); - return Promise.all(requests); - } - - async getRollupData(req: ReqFacade, indexPattern: string) { - const rollupService = await getRollupService(req); - return rollupService - .callAsCurrentUser('rollup.rollupIndexCapabilities', { - indexPattern, - }) - .catch(() => Promise.resolve({})); - } - - async checkForViability(req: ReqFacade, indexPattern: string) { - let isViable = false; - let capabilities = null; - - if (isIndexPatternValid(indexPattern)) { - const rollupData = await this.getRollupData(req, indexPattern); - const rollupIndices = getRollupIndices(rollupData); - - isViable = rollupIndices.length === 1; - - if (isViable) { - const [rollupIndex] = rollupIndices; - const fieldsCapabilities = getCapabilitiesForRollupIndices(rollupData); - - capabilities = new RollupSearchCapabilities(req, fieldsCapabilities, rollupIndex); - } - } - - return { - isViable, - capabilities, - }; - } - - async getFieldsForWildcard( - req: ReqFacade, - indexPattern: string, - { - fieldsCapabilities, - rollupIndex, - }: { fieldsCapabilities: { [key: string]: any }; rollupIndex: string } - ) { - const fields = await super.getFieldsForWildcard(req, indexPattern); - const fieldsFromFieldCapsApi = keyBy(fields, 'name'); - const rollupIndexCapabilities = fieldsCapabilities[rollupIndex].aggs; - - return mergeCapabilitiesWithFields(rollupIndexCapabilities, fieldsFromFieldCapsApi); - } - }; diff --git a/x-pack/plugins/rollup/server/plugin.ts b/x-pack/plugins/rollup/server/plugin.ts index 51920af7c8cbc..3c670f56c7d8f 100644 --- a/x-pack/plugins/rollup/server/plugin.ts +++ b/x-pack/plugins/rollup/server/plugin.ts @@ -24,7 +24,6 @@ import { import { i18n } from '@kbn/i18n'; import { schema } from '@kbn/config-schema'; -import { ReqFacade } from '../../../../src/plugins/vis_type_timeseries/server'; import { PLUGIN, CONFIG_ROLLUPS } from '../common'; import { Dependencies } from './types'; import { registerApiRoutes } from './routes'; @@ -32,7 +31,6 @@ import { License } from './services'; import { registerRollupUsageCollector } from './collectors'; import { rollupDataEnricher } from './rollup_data_enricher'; import { IndexPatternsFetcher } from './shared_imports'; -import { registerRollupSearchStrategy } from './lib/search_strategies'; import { elasticsearchJsPlugin } from './client/elasticsearch_rollup'; import { isEsError } from './shared_imports'; import { formatEsError } from './lib/format_es_error'; @@ -45,6 +43,7 @@ async function getCustomEsClient(getStartServices: CoreSetup['getStartServices'] const [core] = await getStartServices(); // Extend the elasticsearchJs client with additional endpoints. const esClientConfig = { plugins: [elasticsearchJsPlugin] }; + return core.elasticsearch.legacy.createClient('rollup', esClientConfig); } @@ -128,15 +127,6 @@ export class RollupPlugin implements Plugin { }, }); - if (visTypeTimeseries) { - const getRollupService = async (request: ReqFacade) => { - this.rollupEsClient = this.rollupEsClient ?? (await getCustomEsClient(getStartServices)); - return this.rollupEsClient.asScoped(request); - }; - const { addSearchStrategy } = visTypeTimeseries; - registerRollupSearchStrategy(addSearchStrategy, getRollupService); - } - if (usageCollection) { this.globalConfig$ .pipe(first()) diff --git a/x-pack/plugins/runtime_fields/README.md b/x-pack/plugins/runtime_fields/README.md new file mode 100644 index 0000000000000..d4664a3a07c61 --- /dev/null +++ b/x-pack/plugins/runtime_fields/README.md @@ -0,0 +1,197 @@ +# Runtime fields + +Welcome to the home of the runtime field editor and everything related to runtime fields! + +## The runtime field editor + +### Integration + +The recommended way to integrate the runtime fields editor is by adding a plugin dependency to the `"runtimeFields"` x-pack plugin. This way you will be able to lazy load the editor when it is required and it will not increment the bundle size of your plugin. + +```js +// 1. Add the plugin as a dependency in your kibana.json +{ + ... + "requiredBundles": [ + "runtimeFields", + ... + ] +} + +// 2. Access it in your plugin setup() +export class MyPlugin { + setup(core, { runtimeFields }) { + // logic to provide it to your app, probably through context + } +} + +// 3. Load the editor and open it anywhere in your app +const MyComponent = () => { + // Access the plugin through context + const { runtimeFields } = useAppPlugins(); + + // Ref of the handler to close the editor + const closeRuntimeFieldEditor = useRef(() => {}); + + const saveRuntimeField = (field: RuntimeField) => { + // Do something with the field + console.log(field); // { name: 'myField', type: 'boolean', script: "return 'hello'" } + }; + + const openRuntimeFieldsEditor = async() => { + // Lazy load the editor + const { openEditor } = await runtimeFields.loadEditor(); + + closeRuntimeFieldEditor.current = openEditor({ + onSave: saveRuntimeField, + /* defaultValue: optional field to edit */ + }); + }; + + useEffect(() => { + return () => { + // Make sure to remove the editor when the component unmounts + closeRuntimeFieldEditor.current(); + }; + }, []); + + return ( + + ) +} +``` + +#### Alternative + +The runtime field editor is also exported as static React component that you can import into your components. The editor is exported in 2 flavours: + +* As the content of a `` (it contains a flyout header and footer) +* As a standalone component that you can inline anywhere + +**Note:** The runtime field editor uses the `` that has a dependency on the `Provider` from the `"kibana_react"` plugin. If your app is not already wrapped by this provider you will need to add it at least around the runtime field editor. You can see an example in the ["Using the core.overlays.openFlyout()"](#using-the-coreoverlaysopenflyout) example below. + +### Content of a `` + +```js +import React, { useState } from 'react'; +import { EuiFlyoutBody, EuiButton } from '@elastic/eui'; +import { RuntimeFieldEditorFlyoutContent, RuntimeField } from '../runtime_fields/public'; + +const MyComponent = () => { + const { docLinksStart } = useCoreContext(); // access the core start service + const [isFlyoutVisilbe, setIsFlyoutVisible] = useState(false); + + const saveRuntimeField = useCallback((field: RuntimeField) => { + // Do something with the field + }, []); + + return ( + <> + setIsFlyoutVisible(true)}>Create field + + {isFlyoutVisible && ( + setIsFlyoutVisible(false)}> + setIsFlyoutVisible(false)} + docLinks={docLinksStart} + defaultValue={/*optional runtime field to edit*/} + /> + + )} + + ) +} +``` + +#### Using the `core.overlays.openFlyout()` + +As an alternative you can open the flyout with the `openFlyout()` helper from core. + +```js +import React, { useRef } from 'react'; +import { EuiButton } from '@elastic/eui'; +import { OverlayRef } from 'src/core/public'; + +import { createKibanaReactContext, toMountPoint } from '../../src/plugins/kibana_react/public'; +import { RuntimeFieldEditorFlyoutContent, RuntimeField } from '../runtime_fields/public'; + +const MyComponent = () => { + // Access the core start service + const { docLinksStart, overlays, uiSettings } = useCoreContext(); + const flyoutEditor = useRef(null); + + const { openFlyout } = overlays; + + const saveRuntimeField = useCallback((field: RuntimeField) => { + // Do something with the field + }, []); + + const openRuntimeFieldEditor = useCallback(() => { + const { Provider: KibanaReactContextProvider } = createKibanaReactContext({ uiSettings }); + + flyoutEditor.current = openFlyout( + toMountPoint( + + flyoutEditor.current?.close()} + docLinks={docLinksStart} + defaultValue={defaultRuntimeField} + /> + + ) + ); + }, [openFlyout, saveRuntimeField, uiSettings]); + + return ( + <> + Create field + + ) +} +``` + +### Standalone component + +```js +import React, { useState } from 'react'; +import { EuiButton, EuiSpacer } from '@elastic/eui'; +import { RuntimeFieldEditor, RuntimeField, RuntimeFieldFormState } from '../runtime_fields/public'; + +const MyComponent = () => { + const { docLinksStart } = useCoreContext(); // access the core start service + const [runtimeFieldFormState, setRuntimeFieldFormState] = useState({ + isSubmitted: false, + isValid: undefined, + submit: async() => Promise.resolve({ isValid: false, data: {} as RuntimeField }) + }); + + const { submit, isValid: isFormValid, isSubmitted } = runtimeFieldFormState; + + const saveRuntimeField = useCallback(async () => { + const { isValid, data } = await submit(); + if (isValid) { + // Do something with the field (data) + } + }, [submit]); + + return ( + <> + + + + + + Save field + + + ) +} +``` \ No newline at end of file diff --git a/x-pack/plugins/runtime_fields/kibana.json b/x-pack/plugins/runtime_fields/kibana.json new file mode 100644 index 0000000000000..65932c723c474 --- /dev/null +++ b/x-pack/plugins/runtime_fields/kibana.json @@ -0,0 +1,15 @@ +{ + "id": "runtimeFields", + "version": "kibana", + "server": false, + "ui": true, + "requiredPlugins": [ + ], + "optionalPlugins": [ + ], + "configPath": ["xpack", "runtime_fields"], + "requiredBundles": [ + "kibanaReact", + "esUiShared" + ] +} diff --git a/x-pack/plugins/runtime_fields/public/__jest__/setup_environment.tsx b/x-pack/plugins/runtime_fields/public/__jest__/setup_environment.tsx new file mode 100644 index 0000000000000..ccfe426cfdb09 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/__jest__/setup_environment.tsx @@ -0,0 +1,44 @@ +/* + * 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 React from 'react'; + +jest.mock('../../../../../src/plugins/kibana_react/public', () => { + const original = jest.requireActual('../../../../../src/plugins/kibana_react/public'); + + const CodeEditorMock = (props: any) => ( + ) => { + props.onChange(e.target.value); + }} + /> + ); + + return { + ...original, + CodeEditor: CodeEditorMock, + }; +}); + +jest.mock('@elastic/eui', () => { + const original = jest.requireActual('@elastic/eui'); + + return { + ...original, + EuiComboBox: (props: any) => ( + { + props.onChange([syntheticEvent['0']]); + }} + /> + ), + }; +}); diff --git a/x-pack/plugins/runtime_fields/public/components/index.ts b/x-pack/plugins/runtime_fields/public/components/index.ts new file mode 100644 index 0000000000000..86ac968d39f21 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/components/index.ts @@ -0,0 +1,11 @@ +/* + * 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 { RuntimeFieldForm, FormState as RuntimeFieldFormState } from './runtime_field_form'; + +export { RuntimeFieldEditor } from './runtime_field_editor'; + +export { RuntimeFieldEditorFlyoutContent } from './runtime_field_editor_flyout_content'; diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_editor/index.ts b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor/index.ts new file mode 100644 index 0000000000000..62fa0bf991542 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor/index.ts @@ -0,0 +1,7 @@ +/* + * 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 { RuntimeFieldEditor } from './runtime_field_editor'; diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_editor/runtime_field_editor.test.tsx b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor/runtime_field_editor.test.tsx new file mode 100644 index 0000000000000..c56bc16c304ad --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor/runtime_field_editor.test.tsx @@ -0,0 +1,71 @@ +/* + * 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 { act } from 'react-dom/test-utils'; +import { DocLinksStart } from 'src/core/public'; + +import '../../__jest__/setup_environment'; +import { registerTestBed, TestBed } from '../../test_utils'; +import { RuntimeField } from '../../types'; +import { RuntimeFieldForm, FormState } from '../runtime_field_form/runtime_field_form'; +import { RuntimeFieldEditor, Props } from './runtime_field_editor'; + +const setup = (props?: Props) => + registerTestBed(RuntimeFieldEditor, { + memoryRouter: { + wrapComponent: false, + }, + })(props) as TestBed; + +const docLinks: DocLinksStart = { + ELASTIC_WEBSITE_URL: 'https://jestTest.elastic.co', + DOC_LINK_VERSION: 'jest', + links: {} as any, +}; + +describe('Runtime field editor', () => { + let testBed: TestBed; + let onChange: jest.Mock = jest.fn(); + + const lastOnChangeCall = (): FormState[] => onChange.mock.calls[onChange.mock.calls.length - 1]; + + beforeEach(() => { + onChange = jest.fn(); + }); + + test('should render the ', () => { + testBed = setup({ docLinks }); + const { component } = testBed; + + expect(component.find(RuntimeFieldForm).length).toBe(1); + }); + + test('should accept a defaultValue and onChange prop to forward the form state', async () => { + const defaultValue: RuntimeField = { + name: 'foo', + type: 'date', + script: 'test=123', + }; + testBed = setup({ onChange, defaultValue, docLinks }); + + expect(onChange).toHaveBeenCalled(); + + let lastState = lastOnChangeCall()[0]; + expect(lastState.isValid).toBe(undefined); + expect(lastState.isSubmitted).toBe(false); + expect(lastState.submit).toBeDefined(); + + let data; + await act(async () => { + ({ data } = await lastState.submit()); + }); + expect(data).toEqual(defaultValue); + + // Make sure that both isValid and isSubmitted state are now "true" + lastState = lastOnChangeCall()[0]; + expect(lastState.isValid).toBe(true); + expect(lastState.isSubmitted).toBe(true); + }); +}); diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_editor/runtime_field_editor.tsx b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor/runtime_field_editor.tsx new file mode 100644 index 0000000000000..07935be171fd2 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor/runtime_field_editor.tsx @@ -0,0 +1,24 @@ +/* + * 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 React from 'react'; +import { DocLinksStart } from 'src/core/public'; + +import { RuntimeField } from '../../types'; +import { getLinks } from '../../lib'; +import { RuntimeFieldForm, Props as FormProps } from '../runtime_field_form/runtime_field_form'; + +export interface Props { + docLinks: DocLinksStart; + defaultValue?: RuntimeField; + onChange?: FormProps['onChange']; +} + +export const RuntimeFieldEditor = ({ defaultValue, onChange, docLinks }: Props) => { + const links = getLinks(docLinks); + + return ; +}; diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/index.ts b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/index.ts new file mode 100644 index 0000000000000..32234bfcc5600 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/index.ts @@ -0,0 +1,7 @@ +/* + * 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 { RuntimeFieldEditorFlyoutContent } from './runtime_field_editor_flyout_content'; diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/runtime_field_editor_flyout_content.test.tsx b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/runtime_field_editor_flyout_content.test.tsx new file mode 100644 index 0000000000000..8e47472295f45 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/runtime_field_editor_flyout_content.test.tsx @@ -0,0 +1,146 @@ +/* + * 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 { act } from 'react-dom/test-utils'; +import { DocLinksStart } from 'src/core/public'; + +import '../../__jest__/setup_environment'; +import { registerTestBed, TestBed } from '../../test_utils'; +import { RuntimeField } from '../../types'; +import { RuntimeFieldEditorFlyoutContent, Props } from './runtime_field_editor_flyout_content'; + +const setup = (props?: Props) => + registerTestBed(RuntimeFieldEditorFlyoutContent, { + memoryRouter: { + wrapComponent: false, + }, + })(props) as TestBed; + +const docLinks: DocLinksStart = { + ELASTIC_WEBSITE_URL: 'htts://jestTest.elastic.co', + DOC_LINK_VERSION: 'jest', + links: {} as any, +}; + +const noop = () => {}; +const defaultProps = { onSave: noop, onCancel: noop, docLinks }; + +describe('Runtime field editor flyout', () => { + test('should have a flyout title', () => { + const { exists, find } = setup(defaultProps); + + expect(exists('flyoutTitle')).toBe(true); + expect(find('flyoutTitle').text()).toBe('Create new field'); + }); + + test('should allow a runtime field to be provided', () => { + const field: RuntimeField = { + name: 'foo', + type: 'date', + script: 'test=123', + }; + + const { find } = setup({ ...defaultProps, defaultValue: field }); + + expect(find('flyoutTitle').text()).toBe(`Edit ${field.name} field`); + expect(find('nameField.input').props().value).toBe(field.name); + expect(find('typeField').props().value).toBe(field.type); + expect(find('scriptField').props().value).toBe(field.script); + }); + + test('should accept an onSave prop', async () => { + const field: RuntimeField = { + name: 'foo', + type: 'date', + script: 'test=123', + }; + const onSave: jest.Mock = jest.fn(); + + const { find } = setup({ ...defaultProps, onSave, defaultValue: field }); + + await act(async () => { + find('saveFieldButton').simulate('click'); + }); + + expect(onSave).toHaveBeenCalled(); + const fieldReturned: RuntimeField = onSave.mock.calls[onSave.mock.calls.length - 1][0]; + expect(fieldReturned).toEqual(field); + }); + + test('should accept an onCancel prop', () => { + const onCancel = jest.fn(); + const { find } = setup({ ...defaultProps, onCancel }); + + find('closeFlyoutButton').simulate('click'); + + expect(onCancel).toHaveBeenCalled(); + }); + + describe('validation', () => { + test('should validate the fields and prevent saving invalid form', async () => { + const onSave: jest.Mock = jest.fn(); + + const { find, exists, form, component } = setup({ ...defaultProps, onSave }); + + expect(find('saveFieldButton').props().disabled).toBe(false); + + await act(async () => { + find('saveFieldButton').simulate('click'); + }); + component.update(); + + expect(onSave).toHaveBeenCalledTimes(0); + expect(find('saveFieldButton').props().disabled).toBe(true); + expect(form.getErrorsMessages()).toEqual([ + 'Give a name to the field.', + 'Script must emit() a value.', + ]); + expect(exists('formError')).toBe(true); + expect(find('formError').text()).toBe('Fix errors in form before continuing.'); + }); + + test('should forward values from the form', async () => { + const onSave: jest.Mock = jest.fn(); + + const { find, form } = setup({ ...defaultProps, onSave }); + + act(() => { + form.setInputValue('nameField.input', 'someName'); + form.setInputValue('scriptField', 'script=123'); + }); + + await act(async () => { + find('saveFieldButton').simulate('click'); + }); + + expect(onSave).toHaveBeenCalled(); + let fieldReturned: RuntimeField = onSave.mock.calls[onSave.mock.calls.length - 1][0]; + expect(fieldReturned).toEqual({ + name: 'someName', + type: 'keyword', // default to keyword + script: 'script=123', + }); + + // Change the type and make sure it is forwarded + act(() => { + find('typeField').simulate('change', [ + { + label: 'Other type', + value: 'other_type', + }, + ]); + }); + await act(async () => { + find('saveFieldButton').simulate('click'); + }); + fieldReturned = onSave.mock.calls[onSave.mock.calls.length - 1][0]; + expect(fieldReturned).toEqual({ + name: 'someName', + type: 'other_type', + script: 'script=123', + }); + }); + }); +}); diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/runtime_field_editor_flyout_content.tsx b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/runtime_field_editor_flyout_content.tsx new file mode 100644 index 0000000000000..c7454cff0eb15 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/runtime_field_editor_flyout_content.tsx @@ -0,0 +1,146 @@ +/* + * 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 React, { useCallback, useState } from 'react'; +import { i18n } from '@kbn/i18n'; +import { + EuiFlyoutHeader, + EuiFlyoutBody, + EuiFlyoutFooter, + EuiTitle, + EuiFlexGroup, + EuiFlexItem, + EuiButtonEmpty, + EuiButton, + EuiSpacer, + EuiCallOut, +} from '@elastic/eui'; +import { DocLinksStart } from 'src/core/public'; + +import { RuntimeField } from '../../types'; +import { FormState } from '../runtime_field_form'; +import { RuntimeFieldEditor } from '../runtime_field_editor'; + +const geti18nTexts = (field?: RuntimeField) => { + return { + flyoutTitle: field + ? i18n.translate('xpack.runtimeFields.editor.flyoutEditFieldTitle', { + defaultMessage: 'Edit {fieldName} field', + values: { + fieldName: field.name, + }, + }) + : i18n.translate('xpack.runtimeFields.editor.flyoutDefaultTitle', { + defaultMessage: 'Create new field', + }), + closeButtonLabel: i18n.translate('xpack.runtimeFields.editor.flyoutCloseButtonLabel', { + defaultMessage: 'Close', + }), + saveButtonLabel: i18n.translate('xpack.runtimeFields.editor.flyoutSaveButtonLabel', { + defaultMessage: 'Save', + }), + formErrorsCalloutTitle: i18n.translate('xpack.runtimeFields.editor.validationErrorTitle', { + defaultMessage: 'Fix errors in form before continuing.', + }), + }; +}; + +export interface Props { + /** + * Handler for the "save" footer button + */ + onSave: (field: RuntimeField) => void; + /** + * Handler for the "cancel" footer button + */ + onCancel: () => void; + /** + * The docLinks start service from core + */ + docLinks: DocLinksStart; + /** + * An optional runtime field to edit + */ + defaultValue?: RuntimeField; +} + +export const RuntimeFieldEditorFlyoutContent = ({ + onSave, + onCancel, + docLinks, + defaultValue: field, +}: Props) => { + const i18nTexts = geti18nTexts(field); + + const [formState, setFormState] = useState({ + isSubmitted: false, + isValid: field ? true : undefined, + submit: field + ? async () => ({ isValid: true, data: field }) + : async () => ({ isValid: false, data: {} as RuntimeField }), + }); + const { submit, isValid: isFormValid, isSubmitted } = formState; + + const onSaveField = useCallback(async () => { + const { isValid, data } = await submit(); + + if (isValid) { + onSave(data); + } + }, [submit, onSave]); + + return ( + <> + + +

{i18nTexts.flyoutTitle}

+
+
+ + + + + + + {isSubmitted && !isFormValid && ( + <> + + + + )} + + + + onCancel()} + data-test-subj="closeFlyoutButton" + > + {i18nTexts.closeButtonLabel} + + + + + onSaveField()} + data-test-subj="saveFieldButton" + disabled={isSubmitted && !isFormValid} + fill + > + {i18nTexts.saveButtonLabel} + + + + + + ); +}; diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_form/index.ts b/x-pack/plugins/runtime_fields/public/components/runtime_field_form/index.ts new file mode 100644 index 0000000000000..4041a04aec4d1 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_form/index.ts @@ -0,0 +1,7 @@ +/* + * 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 { RuntimeFieldForm, FormState } from './runtime_field_form'; diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_form/runtime_field_form.test.tsx b/x-pack/plugins/runtime_fields/public/components/runtime_field_form/runtime_field_form.test.tsx new file mode 100644 index 0000000000000..1829514856eed --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_form/runtime_field_form.test.tsx @@ -0,0 +1,91 @@ +/* + * 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 { act } from 'react-dom/test-utils'; + +import '../../__jest__/setup_environment'; +import { registerTestBed, TestBed } from '../../test_utils'; +import { RuntimeField } from '../../types'; +import { RuntimeFieldForm, Props, FormState } from './runtime_field_form'; + +const setup = (props?: Props) => + registerTestBed(RuntimeFieldForm, { + memoryRouter: { + wrapComponent: false, + }, + })(props) as TestBed; + +const links = { + painlessSyntax: 'https://jestTest.elastic.co/to-be-defined.html', +}; + +describe('Runtime field form', () => { + let testBed: TestBed; + let onChange: jest.Mock = jest.fn(); + + const lastOnChangeCall = (): FormState[] => onChange.mock.calls[onChange.mock.calls.length - 1]; + + beforeEach(() => { + onChange = jest.fn(); + }); + + test('should render expected 3 fields (name, returnType, script)', () => { + testBed = setup({ links }); + const { exists } = testBed; + + expect(exists('nameField')).toBe(true); + expect(exists('typeField')).toBe(true); + expect(exists('scriptField')).toBe(true); + }); + + test('should have a link to learn more about painless syntax', () => { + testBed = setup({ links }); + const { exists, find } = testBed; + + expect(exists('painlessSyntaxLearnMoreLink')).toBe(true); + expect(find('painlessSyntaxLearnMoreLink').props().href).toBe(links.painlessSyntax); + }); + + test('should accept a "defaultValue" prop', () => { + const defaultValue: RuntimeField = { + name: 'foo', + type: 'date', + script: 'test=123', + }; + testBed = setup({ defaultValue, links }); + const { find } = testBed; + + expect(find('nameField.input').props().value).toBe(defaultValue.name); + expect(find('typeField').props().value).toBe(defaultValue.type); + expect(find('scriptField').props().value).toBe(defaultValue.script); + }); + + test('should accept an "onChange" prop to forward the form state', async () => { + const defaultValue: RuntimeField = { + name: 'foo', + type: 'date', + script: 'test=123', + }; + testBed = setup({ onChange, defaultValue, links }); + + expect(onChange).toHaveBeenCalled(); + + let lastState = lastOnChangeCall()[0]; + expect(lastState.isValid).toBe(undefined); + expect(lastState.isSubmitted).toBe(false); + expect(lastState.submit).toBeDefined(); + + let data; + await act(async () => { + ({ data } = await lastState.submit()); + }); + expect(data).toEqual(defaultValue); + + // Make sure that both isValid and isSubmitted state are now "true" + lastState = lastOnChangeCall()[0]; + expect(lastState.isValid).toBe(true); + expect(lastState.isSubmitted).toBe(true); + }); +}); diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_form/runtime_field_form.tsx b/x-pack/plugins/runtime_fields/public/components/runtime_field_form/runtime_field_form.tsx new file mode 100644 index 0000000000000..6068302f5b269 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_form/runtime_field_form.tsx @@ -0,0 +1,149 @@ +/* + * 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 React, { useEffect } from 'react'; +import { i18n } from '@kbn/i18n'; +import { PainlessLang } from '@kbn/monaco'; +import { + EuiFlexGroup, + EuiFlexItem, + EuiSpacer, + EuiFormRow, + EuiComboBox, + EuiComboBoxOptionOption, + EuiLink, +} from '@elastic/eui'; + +import { useForm, Form, FormHook, UseField, TextField, CodeEditor } from '../../shared_imports'; +import { RuntimeField } from '../../types'; +import { RUNTIME_FIELD_OPTIONS } from '../../constants'; +import { schema } from './schema'; + +export interface FormState { + isValid: boolean | undefined; + isSubmitted: boolean; + submit: FormHook['submit']; +} + +export interface Props { + links: { + painlessSyntax: string; + }; + defaultValue?: RuntimeField; + onChange?: (state: FormState) => void; +} + +const RuntimeFieldFormComp = ({ defaultValue, onChange, links }: Props) => { + const { form } = useForm({ defaultValue, schema }); + const { submit, isValid: isFormValid, isSubmitted } = form; + + useEffect(() => { + if (onChange) { + onChange({ isValid: isFormValid, isSubmitted, submit }); + } + }, [onChange, isFormValid, isSubmitted, submit]); + + return ( +
+ + {/* Name */} + + + + + {/* Return type */} + + path="type"> + {({ label, value, setValue }) => { + if (value === undefined) { + return null; + } + return ( + <> + + { + if (newValue.length === 0) { + // Don't allow clearing the type. One must always be selected + return; + } + setValue(newValue); + }} + isClearable={false} + data-test-subj="typeField" + fullWidth + /> + + + ); + }} + + + + + + + {/* Script */} + path="script"> + {({ value, setValue, label, isValid, getErrorsMessages }) => { + return ( + + + + {i18n.translate('xpack.runtimeFields.form.script.learnMoreLinkText', { + defaultMessage: 'Learn more about syntax.', + })} + + + + } + fullWidth + > + + + ); + }} + + + ); +}; + +export const RuntimeFieldForm = React.memo(RuntimeFieldFormComp); diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_form/schema.ts b/x-pack/plugins/runtime_fields/public/components/runtime_field_form/schema.ts new file mode 100644 index 0000000000000..abb7cf812200f --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_form/schema.ts @@ -0,0 +1,58 @@ +/* + * 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 { i18n } from '@kbn/i18n'; + +import { FormSchema, fieldValidators } from '../../shared_imports'; +import { RUNTIME_FIELD_OPTIONS } from '../../constants'; +import { RuntimeField, RuntimeType, ComboBoxOption } from '../../types'; + +const { emptyField } = fieldValidators; + +export const schema: FormSchema = { + name: { + label: i18n.translate('xpack.runtimeFields.form.nameLabel', { + defaultMessage: 'Name', + }), + validations: [ + { + validator: emptyField( + i18n.translate('xpack.runtimeFields.form.validations.nameIsRequiredErrorMessage', { + defaultMessage: 'Give a name to the field.', + }) + ), + }, + ], + }, + type: { + label: i18n.translate('xpack.runtimeFields.form.runtimeTypeLabel', { + defaultMessage: 'Type', + }), + defaultValue: 'keyword', + deserializer: (fieldType?: RuntimeType) => { + if (!fieldType) { + return []; + } + + const label = RUNTIME_FIELD_OPTIONS.find(({ value }) => value === fieldType)?.label; + return [{ label: label ?? fieldType, value: fieldType }]; + }, + serializer: (value: Array>) => value[0].value!, + }, + script: { + label: i18n.translate('xpack.runtimeFields.form.defineFieldLabel', { + defaultMessage: 'Define field', + }), + validations: [ + { + validator: emptyField( + i18n.translate('xpack.runtimeFields.form.validations.scriptIsRequiredErrorMessage', { + defaultMessage: 'Script must emit() a value.', + }) + ), + }, + ], + }, +}; diff --git a/x-pack/plugins/runtime_fields/public/constants.ts b/x-pack/plugins/runtime_fields/public/constants.ts new file mode 100644 index 0000000000000..017b58c246afe --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/constants.ts @@ -0,0 +1,37 @@ +/* + * 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 { ComboBoxOption } from './types'; + +export const RUNTIME_FIELD_TYPES = ['keyword', 'long', 'double', 'date', 'ip', 'boolean'] as const; + +type RuntimeType = typeof RUNTIME_FIELD_TYPES[number]; + +export const RUNTIME_FIELD_OPTIONS: Array> = [ + { + label: 'Keyword', + value: 'keyword', + }, + { + label: 'Long', + value: 'long', + }, + { + label: 'Double', + value: 'double', + }, + { + label: 'Date', + value: 'date', + }, + { + label: 'IP', + value: 'ip', + }, + { + label: 'Boolean', + value: 'boolean', + }, +]; diff --git a/x-pack/plugins/runtime_fields/public/index.ts b/x-pack/plugins/runtime_fields/public/index.ts new file mode 100644 index 0000000000000..0eab32c0b3d97 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/index.ts @@ -0,0 +1,18 @@ +/* + * 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 { RuntimeFieldsPlugin } from './plugin'; + +export { + RuntimeFieldEditorFlyoutContent, + RuntimeFieldEditor, + RuntimeFieldFormState, +} from './components'; +export { RUNTIME_FIELD_OPTIONS } from './constants'; +export { RuntimeField, RuntimeType, PluginSetup as RuntimeFieldsSetup } from './types'; + +export function plugin() { + return new RuntimeFieldsPlugin(); +} diff --git a/x-pack/plugins/runtime_fields/public/lib/documentation.ts b/x-pack/plugins/runtime_fields/public/lib/documentation.ts new file mode 100644 index 0000000000000..87eab8b7ed997 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/lib/documentation.ts @@ -0,0 +1,16 @@ +/* + * 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 { DocLinksStart } from 'src/core/public'; + +export const getLinks = (docLinks: DocLinksStart) => { + const { DOC_LINK_VERSION, ELASTIC_WEBSITE_URL } = docLinks; + const docsBase = `${ELASTIC_WEBSITE_URL}guide/en`; + const painlessDocsBase = `${docsBase}/elasticsearch/painless/${DOC_LINK_VERSION}`; + + return { + painlessSyntax: `${painlessDocsBase}/painless-lang-spec.html`, + }; +}; diff --git a/x-pack/plugins/runtime_fields/public/lib/index.ts b/x-pack/plugins/runtime_fields/public/lib/index.ts new file mode 100644 index 0000000000000..11c9914bf2e81 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/lib/index.ts @@ -0,0 +1,7 @@ +/* + * 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 { getLinks } from './documentation'; diff --git a/x-pack/plugins/runtime_fields/public/load_editor.tsx b/x-pack/plugins/runtime_fields/public/load_editor.tsx new file mode 100644 index 0000000000000..f1b9c495f0336 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/load_editor.tsx @@ -0,0 +1,57 @@ +/* + * 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 React from 'react'; +import { CoreSetup, OverlayRef } from 'src/core/public'; + +import { toMountPoint, createKibanaReactContext } from './shared_imports'; +import { LoadEditorResponse, RuntimeField } from './types'; + +export interface OpenRuntimeFieldEditorProps { + onSave(field: RuntimeField): void; + defaultValue?: RuntimeField; +} + +export const getRuntimeFieldEditorLoader = (coreSetup: CoreSetup) => async (): Promise< + LoadEditorResponse +> => { + const { RuntimeFieldEditorFlyoutContent } = await import('./components'); + const [core] = await coreSetup.getStartServices(); + const { uiSettings, overlays, docLinks } = core; + const { Provider: KibanaReactContextProvider } = createKibanaReactContext({ uiSettings }); + + let overlayRef: OverlayRef | null = null; + + const openEditor = ({ onSave, defaultValue }: OpenRuntimeFieldEditorProps) => { + const closeEditor = () => { + overlayRef?.close(); + overlayRef = null; + }; + + const onSaveField = (field: RuntimeField) => { + closeEditor(); + onSave(field); + }; + + overlayRef = overlays.openFlyout( + toMountPoint( + + overlayRef?.close()} + docLinks={docLinks} + defaultValue={defaultValue} + /> + + ) + ); + + return closeEditor; + }; + + return { + openEditor, + }; +}; diff --git a/x-pack/plugins/runtime_fields/public/plugin.test.ts b/x-pack/plugins/runtime_fields/public/plugin.test.ts new file mode 100644 index 0000000000000..07f7a3553d0d3 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/plugin.test.ts @@ -0,0 +1,82 @@ +/* + * 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 { CoreSetup } from 'src/core/public'; +import { coreMock } from 'src/core/public/mocks'; + +jest.mock('../../../../src/plugins/kibana_react/public', () => { + const original = jest.requireActual('../../../../src/plugins/kibana_react/public'); + + return { + ...original, + toMountPoint: (node: React.ReactNode) => node, + }; +}); + +import { StartPlugins, PluginStart } from './types'; +import { RuntimeFieldEditorFlyoutContent } from './components'; +import { RuntimeFieldsPlugin } from './plugin'; + +const noop = () => {}; + +describe('RuntimeFieldsPlugin', () => { + let coreSetup: CoreSetup; + let plugin: RuntimeFieldsPlugin; + + beforeEach(() => { + plugin = new RuntimeFieldsPlugin(); + coreSetup = coreMock.createSetup(); + }); + + test('should return a handler to load the runtime field editor', async () => { + const setupApi = await plugin.setup(coreSetup, {}); + expect(setupApi.loadEditor).toBeDefined(); + }); + + test('once it is loaded it should expose a handler to open the editor', async () => { + const setupApi = await plugin.setup(coreSetup, {}); + const response = await setupApi.loadEditor(); + expect(response.openEditor).toBeDefined(); + }); + + test('should call core.overlays.openFlyout when opening the editor', async () => { + const openFlyout = jest.fn(); + const onSaveSpy = jest.fn(); + + const mockCore = { + overlays: { + openFlyout, + }, + uiSettings: {}, + }; + coreSetup.getStartServices = async () => [mockCore] as any; + const setupApi = await plugin.setup(coreSetup, {}); + const { openEditor } = await setupApi.loadEditor(); + + openEditor({ onSave: onSaveSpy }); + + expect(openFlyout).toHaveBeenCalled(); + + const [[arg]] = openFlyout.mock.calls; + expect(arg.props.children.type).toBe(RuntimeFieldEditorFlyoutContent); + + // We force call the "onSave" prop from the component + // and make sure that the the spy is being called. + // Note: we are testing implementation details, if we change or rename the "onSave" prop on + // the component, we will need to update this test accordingly. + expect(arg.props.children.props.onSave).toBeDefined(); + arg.props.children.props.onSave(); + expect(onSaveSpy).toHaveBeenCalled(); + }); + + test('should return a handler to close the flyout', async () => { + const setupApi = await plugin.setup(coreSetup, {}); + const { openEditor } = await setupApi.loadEditor(); + + const closeEditorHandler = openEditor({ onSave: noop }); + expect(typeof closeEditorHandler).toBe('function'); + }); +}); diff --git a/x-pack/plugins/runtime_fields/public/plugin.ts b/x-pack/plugins/runtime_fields/public/plugin.ts new file mode 100644 index 0000000000000..ebc8b98db66ba --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/plugin.ts @@ -0,0 +1,26 @@ +/* + * 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 { Plugin, CoreSetup, CoreStart } from 'src/core/public'; + +import { PluginSetup, PluginStart, SetupPlugins, StartPlugins } from './types'; +import { getRuntimeFieldEditorLoader } from './load_editor'; + +export class RuntimeFieldsPlugin + implements Plugin { + public setup(core: CoreSetup, plugins: SetupPlugins): PluginSetup { + return { + loadEditor: getRuntimeFieldEditorLoader(core), + }; + } + + public start(core: CoreStart, plugins: StartPlugins) { + return {}; + } + + public stop() { + return {}; + } +} diff --git a/x-pack/plugins/runtime_fields/public/shared_imports.ts b/x-pack/plugins/runtime_fields/public/shared_imports.ts new file mode 100644 index 0000000000000..200a68ab71031 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/shared_imports.ts @@ -0,0 +1,23 @@ +/* + * 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 { + useForm, + Form, + FormSchema, + UseField, + FormHook, +} from '../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; + +export { fieldValidators } from '../../../../src/plugins/es_ui_shared/static/forms/helpers'; + +export { TextField } from '../../../../src/plugins/es_ui_shared/static/forms/components'; + +export { + CodeEditor, + toMountPoint, + createKibanaReactContext, +} from '../../../../src/plugins/kibana_react/public'; diff --git a/x-pack/plugins/runtime_fields/public/test_utils.ts b/x-pack/plugins/runtime_fields/public/test_utils.ts new file mode 100644 index 0000000000000..966db01ef1532 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/test_utils.ts @@ -0,0 +1,7 @@ +/* + * 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 { registerTestBed, TestBed } from '@kbn/test/jest'; diff --git a/x-pack/plugins/runtime_fields/public/types.ts b/x-pack/plugins/runtime_fields/public/types.ts new file mode 100644 index 0000000000000..4172061540af8 --- /dev/null +++ b/x-pack/plugins/runtime_fields/public/types.ts @@ -0,0 +1,40 @@ +/* + * 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 { DataPublicPluginStart } from 'src/plugins/data/public'; + +import { RUNTIME_FIELD_TYPES } from './constants'; +import { OpenRuntimeFieldEditorProps } from './load_editor'; + +export interface LoadEditorResponse { + openEditor(props: OpenRuntimeFieldEditorProps): () => void; +} + +export interface PluginSetup { + loadEditor(): Promise; +} + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface PluginStart {} + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface SetupPlugins {} + +export interface StartPlugins { + data: DataPublicPluginStart; +} + +export type RuntimeType = typeof RUNTIME_FIELD_TYPES[number]; + +export interface RuntimeField { + name: string; + type: RuntimeType; + script: string; +} + +export interface ComboBoxOption { + label: string; + value?: T; +} diff --git a/x-pack/plugins/saved_objects_tagging/common/test_utils/index.ts b/x-pack/plugins/saved_objects_tagging/common/test_utils/index.ts index 80d2dbc0b1566..7f6e2a12d9e53 100644 --- a/x-pack/plugins/saved_objects_tagging/common/test_utils/index.ts +++ b/x-pack/plugins/saved_objects_tagging/common/test_utils/index.ts @@ -6,6 +6,7 @@ import { SavedObject, SavedObjectReference } from 'src/core/types'; import { Tag, TagAttributes } from '../types'; +import { TagsCapabilities } from '../capabilities'; export const createTagReference = (id: string): SavedObjectReference => ({ type: 'tag', @@ -35,3 +36,13 @@ export const createTagAttributes = (parts: Partial = {}): TagAttr color: '#FF00CC', ...parts, }); + +export const createTagCapabilities = (parts: Partial = {}): TagsCapabilities => ({ + view: true, + create: true, + edit: true, + delete: true, + assign: true, + viewConnections: true, + ...parts, +}); diff --git a/x-pack/plugins/saved_objects_tagging/public/components/edition_modal/create_or_edit_modal.tsx b/x-pack/plugins/saved_objects_tagging/public/components/edition_modal/create_or_edit_modal.tsx index 7baebdae2493e..1a80c0598f97a 100644 --- a/x-pack/plugins/saved_objects_tagging/public/components/edition_modal/create_or_edit_modal.tsx +++ b/x-pack/plugins/saved_objects_tagging/public/components/edition_modal/create_or_edit_modal.tsx @@ -22,6 +22,7 @@ import { EuiTextArea, EuiSpacer, EuiText, + htmlIdGenerator, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -52,6 +53,7 @@ export const CreateOrEditModal: FC = ({ tag, mode, }) => { + const optionalMessageId = htmlIdGenerator()(); const ifMounted = useIfMounted(); const [submitting, setSubmitting] = useState(false); @@ -139,6 +141,12 @@ export const CreateOrEditModal: FC = ({ onClick={() => setColor(getRandomColor())} size="xs" style={{ height: '18px', fontSize: '0.75rem' }} + aria-label={i18n.translate( + 'xpack.savedObjectsTagging.management.createModal.color.randomizeAriaLabel', + { + defaultMessage: 'Randomize tag color', + } + )} > = ({ defaultMessage: 'Description', })} labelAppend={ - + = ({ resize="none" fullWidth={true} compressed={true} + aria-describedby={optionalMessageId} />
diff --git a/x-pack/plugins/saved_objects_tagging/public/management/actions/bulk_delete.test.ts b/x-pack/plugins/saved_objects_tagging/public/management/actions/bulk_delete.test.ts new file mode 100644 index 0000000000000..42a4e628bef4e --- /dev/null +++ b/x-pack/plugins/saved_objects_tagging/public/management/actions/bulk_delete.test.ts @@ -0,0 +1,67 @@ +/* + * 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 { + overlayServiceMock, + notificationServiceMock, +} from '../../../../../../src/core/public/mocks'; +import { tagClientMock } from '../../tags/tags_client.mock'; +import { TagBulkAction } from '../types'; +import { getBulkDeleteAction } from './bulk_delete'; + +describe('bulkDeleteAction', () => { + let tagClient: ReturnType; + let overlays: ReturnType; + let notifications: ReturnType; + let setLoading: jest.MockedFunction<(loading: boolean) => void>; + let action: TagBulkAction; + + const tagIds = ['id-1', 'id-2', 'id-3']; + + beforeEach(() => { + tagClient = tagClientMock.create(); + overlays = overlayServiceMock.createStartContract(); + notifications = notificationServiceMock.createStartContract(); + setLoading = jest.fn(); + + action = getBulkDeleteAction({ tagClient, overlays, notifications, setLoading }); + }); + + it('performs the operation if the confirmation is accepted', async () => { + overlays.openConfirm.mockResolvedValue(true); + + await action.execute(tagIds); + + expect(overlays.openConfirm).toHaveBeenCalledTimes(1); + + expect(tagClient.bulkDelete).toHaveBeenCalledTimes(1); + expect(tagClient.bulkDelete).toHaveBeenCalledWith(tagIds); + + expect(notifications.toasts.addSuccess).toHaveBeenCalledTimes(1); + }); + + it('does not perform the operation if the confirmation is rejected', async () => { + overlays.openConfirm.mockResolvedValue(false); + + await action.execute(tagIds); + + expect(overlays.openConfirm).toHaveBeenCalledTimes(1); + + expect(tagClient.bulkDelete).not.toHaveBeenCalled(); + expect(notifications.toasts.addSuccess).not.toHaveBeenCalled(); + }); + + it('does not show notification if `client.bulkDelete` rejects ', async () => { + overlays.openConfirm.mockResolvedValue(true); + tagClient.bulkDelete.mockRejectedValue(new Error('error calling bulkDelete')); + + await expect(action.execute(tagIds)).rejects.toMatchInlineSnapshot( + `[Error: error calling bulkDelete]` + ); + + expect(notifications.toasts.addSuccess).not.toHaveBeenCalled(); + }); +}); diff --git a/x-pack/plugins/saved_objects_tagging/public/management/actions/bulk_delete.ts b/x-pack/plugins/saved_objects_tagging/public/management/actions/bulk_delete.ts new file mode 100644 index 0000000000000..6d9c14d330007 --- /dev/null +++ b/x-pack/plugins/saved_objects_tagging/public/management/actions/bulk_delete.ts @@ -0,0 +1,92 @@ +/* + * 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 { OverlayStart, NotificationsStart } from 'src/core/public'; +import { i18n } from '@kbn/i18n'; +import { ITagInternalClient } from '../../tags'; +import { TagBulkAction } from '../types'; + +interface GetBulkDeleteActionOptions { + overlays: OverlayStart; + notifications: NotificationsStart; + tagClient: ITagInternalClient; + setLoading: (loading: boolean) => void; +} + +export const getBulkDeleteAction = ({ + overlays, + notifications, + tagClient, + setLoading, +}: GetBulkDeleteActionOptions): TagBulkAction => { + return { + id: 'delete', + label: i18n.translate('xpack.savedObjectsTagging.management.actions.bulkDelete.label', { + defaultMessage: 'Delete', + }), + 'aria-label': i18n.translate( + 'xpack.savedObjectsTagging.management.actions.bulkDelete.ariaLabel', + { + defaultMessage: 'Delete selected tags', + } + ), + icon: 'trash', + refreshAfterExecute: true, + execute: async (tagIds) => { + const confirmed = await overlays.openConfirm( + i18n.translate('xpack.savedObjectsTagging.management.actions.bulkDelete.confirm.text', { + defaultMessage: + 'By deleting {count, plural, one {this tag} other {these tags}}, you will no longer be able to assign {count, plural, one {it} other {them}} to saved objects. ' + + '{count, plural, one {This tag} other {These tags}} will be removed from any saved objects that currently use {count, plural, one {it} other {them}}. ' + + 'Are you sure you wish to proceed?', + values: { + count: tagIds.length, + }, + }), + { + title: i18n.translate( + 'xpack.savedObjectsTagging.management.actions.bulkDelete.confirm.title', + { + defaultMessage: 'Delete {count, plural, one {1 tag} other {# tags}}', + values: { + count: tagIds.length, + }, + } + ), + confirmButtonText: i18n.translate( + 'xpack.savedObjectsTagging.management.actions.bulkDelete.confirm.confirmButtonText', + { + defaultMessage: 'Delete {count, plural, one {tag} other {tags}}', + values: { + count: tagIds.length, + }, + } + ), + buttonColor: 'danger', + maxWidth: 560, + } + ); + + if (confirmed) { + setLoading(true); + await tagClient.bulkDelete(tagIds); + setLoading(false); + + notifications.toasts.addSuccess({ + title: i18n.translate( + 'xpack.savedObjectsTagging.management.actions.bulkDelete.notification.successTitle', + { + defaultMessage: 'Deleted {count, plural, one {1 tag} other {# tags}}', + values: { + count: tagIds.length, + }, + } + ), + }); + } + }, + }; +}; diff --git a/x-pack/plugins/saved_objects_tagging/public/management/actions/clear_selection.ts b/x-pack/plugins/saved_objects_tagging/public/management/actions/clear_selection.ts new file mode 100644 index 0000000000000..79212be98236c --- /dev/null +++ b/x-pack/plugins/saved_objects_tagging/public/management/actions/clear_selection.ts @@ -0,0 +1,28 @@ +/* + * 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 { i18n } from '@kbn/i18n'; +import { TagBulkAction } from '../types'; + +interface GetClearSelectionActionOptions { + clearSelection: () => void; +} + +export const getClearSelectionAction = ({ + clearSelection, +}: GetClearSelectionActionOptions): TagBulkAction => { + return { + id: 'clear_selection', + label: i18n.translate('xpack.savedObjectsTagging.management.actions.clearSelection.label', { + defaultMessage: 'Clear selection', + }), + icon: 'cross', + refreshAfterExecute: true, + execute: async () => { + clearSelection(); + }, + }; +}; diff --git a/x-pack/plugins/saved_objects_tagging/public/management/actions/index.test.ts b/x-pack/plugins/saved_objects_tagging/public/management/actions/index.test.ts new file mode 100644 index 0000000000000..5325d4ee97cf8 --- /dev/null +++ b/x-pack/plugins/saved_objects_tagging/public/management/actions/index.test.ts @@ -0,0 +1,48 @@ +/* + * 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 { coreMock } from '../../../../../../src/core/public/mocks'; +import { createTagCapabilities } from '../../../common/test_utils'; +import { TagsCapabilities } from '../../../common/capabilities'; +import { tagClientMock } from '../../tags/tags_client.mock'; +import { TagBulkAction } from '../types'; + +import { getBulkActions } from './index'; + +describe('getBulkActions', () => { + let core: ReturnType; + let tagClient: ReturnType; + let clearSelection: jest.MockedFunction<() => void>; + let setLoading: jest.MockedFunction<(loading: boolean) => void>; + + beforeEach(() => { + core = coreMock.createStart(); + tagClient = tagClientMock.create(); + clearSelection = jest.fn(); + setLoading = jest.fn(); + }); + + const getActions = (caps: Partial) => + getBulkActions({ + core, + tagClient, + clearSelection, + setLoading, + capabilities: createTagCapabilities(caps), + }); + + const getIds = (actions: TagBulkAction[]) => actions.map((action) => action.id); + + it('only returns the `delete` action if user got `delete` permission', () => { + let actions = getActions({ delete: true }); + + expect(getIds(actions)).toContain('delete'); + + actions = getActions({ delete: false }); + + expect(getIds(actions)).not.toContain('delete'); + }); +}); diff --git a/x-pack/plugins/saved_objects_tagging/public/management/actions/index.ts b/x-pack/plugins/saved_objects_tagging/public/management/actions/index.ts new file mode 100644 index 0000000000000..182f0013251df --- /dev/null +++ b/x-pack/plugins/saved_objects_tagging/public/management/actions/index.ts @@ -0,0 +1,43 @@ +/* + * 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 { CoreStart } from 'src/core/public'; +import { TagsCapabilities } from '../../../common'; +import { ITagInternalClient } from '../../tags'; +import { TagBulkAction } from '../types'; +import { getBulkDeleteAction } from './bulk_delete'; +import { getClearSelectionAction } from './clear_selection'; + +interface GetBulkActionOptions { + core: CoreStart; + capabilities: TagsCapabilities; + tagClient: ITagInternalClient; + clearSelection: () => void; + setLoading: (loading: boolean) => void; +} + +export const getBulkActions = ({ + core: { notifications, overlays }, + capabilities, + tagClient, + clearSelection, + setLoading, +}: GetBulkActionOptions): TagBulkAction[] => { + const actions: TagBulkAction[] = []; + + if (capabilities.delete) { + actions.push(getBulkDeleteAction({ notifications, overlays, tagClient, setLoading })); + } + + // only add clear selection if user has permission to perform any other action + // as having at least one action will show the bulk action menu, and the selection column on the table + // and we want to avoid doing that only for the 'unselect' action. + if (actions.length > 0) { + actions.push(getClearSelectionAction({ clearSelection })); + } + + return actions; +}; diff --git a/x-pack/plugins/saved_objects_tagging/public/management/components/_action_bar.scss b/x-pack/plugins/saved_objects_tagging/public/management/components/_action_bar.scss new file mode 100644 index 0000000000000..6858e70e49e8f --- /dev/null +++ b/x-pack/plugins/saved_objects_tagging/public/management/components/_action_bar.scss @@ -0,0 +1,17 @@ +.tagMgt__actionBar + .euiSpacer { + display: none; +} + +.tagMgt__actionBarDivider { + height: $euiSize; + border-right: $euiBorderThin; +} + +.tagMgt__actionBar { + border-bottom: $euiBorderThin; + padding-bottom: $euiSizeS; +} + +.tagMgt__actionBarIcon { + margin-left: $euiSizeXS; +} diff --git a/x-pack/plugins/saved_objects_tagging/public/management/components/action_bar.tsx b/x-pack/plugins/saved_objects_tagging/public/management/components/action_bar.tsx new file mode 100644 index 0000000000000..15d8f155f6246 --- /dev/null +++ b/x-pack/plugins/saved_objects_tagging/public/management/components/action_bar.tsx @@ -0,0 +1,122 @@ +/* + * 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 React, { useState, useCallback, useMemo, FC } from 'react'; +import { + EuiPopover, + EuiFlexItem, + EuiFlexGroup, + EuiContextMenu, + EuiContextMenuPanelItemDescriptor, + EuiText, + EuiLink, + EuiIcon, +} from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { TagBulkAction } from '../types'; + +import './_action_bar.scss'; + +export interface ActionBarProps { + actions: TagBulkAction[]; + totalCount: number; + selectedCount: number; + onActionSelected: (action: TagBulkAction) => void; +} + +const actionToMenuItem = ( + action: TagBulkAction, + onActionSelected: (action: TagBulkAction) => void, + closePopover: () => void +): EuiContextMenuPanelItemDescriptor => { + return { + name: action.label, + icon: action.icon, + onClick: () => { + closePopover(); + onActionSelected(action); + }, + 'data-test-subj': `actionBar-button-${action.id}`, + }; +}; + +export const ActionBar: FC = ({ + actions, + onActionSelected, + selectedCount, + totalCount, +}) => { + const [isPopoverOpened, setPopOverOpened] = useState(false); + + const closePopover = useCallback(() => { + setPopOverOpened(false); + }, [setPopOverOpened]); + + const togglePopover = useCallback(() => { + setPopOverOpened((opened) => !opened); + }, [setPopOverOpened]); + + const contextMenuPanels = useMemo(() => { + return [ + { + id: 0, + items: actions.map((action) => actionToMenuItem(action, onActionSelected, closePopover)), + }, + ]; + }, [actions, onActionSelected, closePopover]); + + return ( +
+ + + + + + + {selectedCount > 0 && ( + <> + +
+ + + + + + + + + } + > + + + + + )} + +
+ ); +}; diff --git a/x-pack/plugins/saved_objects_tagging/public/management/components/index.ts b/x-pack/plugins/saved_objects_tagging/public/management/components/index.ts index 8435aa0431c23..a28e3523d7af6 100644 --- a/x-pack/plugins/saved_objects_tagging/public/management/components/index.ts +++ b/x-pack/plugins/saved_objects_tagging/public/management/components/index.ts @@ -6,3 +6,4 @@ export { Header } from './header'; export { TagTable } from './table'; +export { ActionBar } from './action_bar'; diff --git a/x-pack/plugins/saved_objects_tagging/public/management/components/table.tsx b/x-pack/plugins/saved_objects_tagging/public/management/components/table.tsx index e86977c60ade1..ed1903fca2495 100644 --- a/x-pack/plugins/saved_objects_tagging/public/management/components/table.tsx +++ b/x-pack/plugins/saved_objects_tagging/public/management/components/table.tsx @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useRef, useEffect, FC } from 'react'; -import { EuiInMemoryTable, EuiBasicTableColumn, EuiLink } from '@elastic/eui'; +import React, { useRef, useEffect, FC, ReactNode } from 'react'; +import { EuiInMemoryTable, EuiBasicTableColumn, EuiLink, Query } from '@elastic/eui'; import { Action as EuiTableAction } from '@elastic/eui/src/components/basic_table/action_types'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -16,12 +16,16 @@ interface TagTableProps { loading: boolean; capabilities: TagsCapabilities; tags: TagWithRelations[]; + initialQuery?: Query; + allowSelection: boolean; + onQueryChange: (query?: Query) => void; selectedTags: TagWithRelations[]; onSelectionChange: (selection: TagWithRelations[]) => void; onEdit: (tag: TagWithRelations) => void; onDelete: (tag: TagWithRelations) => void; getTagRelationUrl: (tag: TagWithRelations) => string; onShowRelations: (tag: TagWithRelations) => void; + actionBar: ReactNode; } const tablePagination = { @@ -43,11 +47,16 @@ export const TagTable: FC = ({ loading, capabilities, tags, + initialQuery, + allowSelection, + onQueryChange, selectedTags, + onSelectionChange, onEdit, onDelete, onShowRelations, getTagRelationUrl, + actionBar, }) => { const tableRef = useRef>(null); @@ -60,9 +69,11 @@ export const TagTable: FC = ({ const actions: Array> = []; if (capabilities.edit) { actions.push({ - name: i18n.translate('xpack.savedObjectsTagging.management.table.actions.edit.title', { - defaultMessage: 'Edit', - }), + name: ({ name }) => + i18n.translate('xpack.savedObjectsTagging.management.table.actions.edit.title', { + defaultMessage: 'Edit {name} tag', + values: { name }, + }), description: i18n.translate( 'xpack.savedObjectsTagging.management.table.actions.edit.description', { @@ -77,9 +88,11 @@ export const TagTable: FC = ({ } if (capabilities.delete) { actions.push({ - name: i18n.translate('xpack.savedObjectsTagging.management.table.actions.delete.title', { - defaultMessage: 'Delete', - }), + name: ({ name }) => + i18n.translate('xpack.savedObjectsTagging.management.table.actions.delete.title', { + defaultMessage: 'Delete {name} tag', + values: { name }, + }), description: i18n.translate( 'xpack.savedObjectsTagging.management.table.actions.delete.description', { @@ -171,13 +184,30 @@ export const TagTable: FC = ({ { + onQueryChange(query || undefined); + }, box: { 'data-test-subj': 'tagsManagementSearchBar', incremental: true, diff --git a/x-pack/plugins/saved_objects_tagging/public/management/tag_management_page.tsx b/x-pack/plugins/saved_objects_tagging/public/management/tag_management_page.tsx index 4afb15bec6243..6b0e17a945c06 100644 --- a/x-pack/plugins/saved_objects_tagging/public/management/tag_management_page.tsx +++ b/x-pack/plugins/saved_objects_tagging/public/management/tag_management_page.tsx @@ -6,13 +6,15 @@ import React, { useEffect, useCallback, useState, useMemo, FC } from 'react'; import useMount from 'react-use/lib/useMount'; -import { EuiPageContent } from '@elastic/eui'; +import { EuiPageContent, Query } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ChromeBreadcrumb, CoreStart } from 'src/core/public'; import { TagWithRelations, TagsCapabilities } from '../../common'; import { getCreateModalOpener, getEditModalOpener } from '../components/edition_modal'; import { ITagInternalClient } from '../tags'; -import { Header, TagTable } from './components'; +import { TagBulkAction } from './types'; +import { Header, TagTable, ActionBar } from './components'; +import { getBulkActions } from './actions'; import { getTagConnectionsUrl } from './utils'; interface TagManagementPageParams { @@ -32,6 +34,21 @@ export const TagManagementPage: FC = ({ const [loading, setLoading] = useState(false); const [allTags, setAllTags] = useState([]); const [selectedTags, setSelectedTags] = useState([]); + const [query, setQuery] = useState(); + + const filteredTags = useMemo(() => { + return query ? Query.execute(query, allTags) : allTags; + }, [allTags, query]); + + const bulkActions = useMemo(() => { + return getBulkActions({ + core, + capabilities, + tagClient, + setLoading, + clearSelection: () => setSelectedTags([]), + }); + }, [core, capabilities, tagClient]); const createModalOpener = useMemo(() => getCreateModalOpener({ overlays, tagClient }), [ overlays, @@ -140,13 +157,12 @@ export const TagManagementPage: FC = ({ } ), buttonColor: 'danger', + maxWidth: 560, } ); if (confirmed) { await tagClient.delete(tag.id); - fetchTags(); - notifications.toasts.addSuccess({ title: i18n.translate('xpack.savedObjectsTagging.notifications.deleteTagSuccessTitle', { defaultMessage: 'Deleted "{name}" tag', @@ -155,18 +171,59 @@ export const TagManagementPage: FC = ({ }, }), }); + + await fetchTags(); } }, [overlays, notifications, fetchTags, tagClient] ); + const executeBulkAction = useCallback( + async (action: TagBulkAction) => { + try { + await action.execute(selectedTags.map(({ id }) => id)); + } catch (e) { + notifications.toasts.addError(e, { + title: i18n.translate('xpack.savedObjectsTagging.notifications.bulkActionError', { + defaultMessage: 'An error occurred', + }), + }); + } finally { + setLoading(false); + } + if (action.refreshAfterExecute) { + await fetchTags(); + } + }, + [selectedTags, fetchTags, notifications] + ); + + const actionBar = useMemo( + () => ( + + ), + [selectedTags, filteredTags, bulkActions, executeBulkAction] + ); + return (
{ + setQuery(newQuery); + setSelectedTags([]); + }} + allowSelection={bulkActions.length > 0} selectedTags={selectedTags} onSelectionChange={(tags) => { setSelectedTags(tags); diff --git a/x-pack/plugins/saved_objects_tagging/public/management/types.ts b/x-pack/plugins/saved_objects_tagging/public/management/types.ts new file mode 100644 index 0000000000000..fc15785142431 --- /dev/null +++ b/x-pack/plugins/saved_objects_tagging/public/management/types.ts @@ -0,0 +1,37 @@ +/* + * 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 { EuiIconType } from '@elastic/eui/src/components/icon/icon'; + +/** + * Represents a tag `bulk action` + */ +export interface TagBulkAction { + /** + * The unique identifier for this action. + */ + id: string; + /** + * The label displayed in the bulk action context menu. + */ + label: string; + /** + * Optional aria-label if the visual label isn't descriptive enough. + */ + 'aria-label'?: string; + /** + * An optional icon to display before the label in the context menu. + */ + icon?: EuiIconType; + /** + * Handler to execute this action against the given list of selected tag ids. + */ + execute: (tagIds: string[]) => void | Promise; + /** + * If true, the list of tags will be reloaded after the action's execution. Defaults to false. + */ + refreshAfterExecute?: boolean; +} diff --git a/x-pack/plugins/saved_objects_tagging/public/tags/tags_client.mock.ts b/x-pack/plugins/saved_objects_tagging/public/tags/tags_client.mock.ts new file mode 100644 index 0000000000000..4ef0e89ae4866 --- /dev/null +++ b/x-pack/plugins/saved_objects_tagging/public/tags/tags_client.mock.ts @@ -0,0 +1,25 @@ +/* + * 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 { ITagInternalClient } from './tags_client'; + +const createInternalClientMock = () => { + const mock: jest.Mocked = { + create: jest.fn(), + get: jest.fn(), + getAll: jest.fn(), + delete: jest.fn(), + update: jest.fn(), + find: jest.fn(), + bulkDelete: jest.fn(), + }; + + return mock; +}; + +export const tagClientMock = { + create: createInternalClientMock, +}; diff --git a/x-pack/plugins/saved_objects_tagging/public/tags/tags_client.test.ts b/x-pack/plugins/saved_objects_tagging/public/tags/tags_client.test.ts index ac73880e52949..576f89b796010 100644 --- a/x-pack/plugins/saved_objects_tagging/public/tags/tags_client.test.ts +++ b/x-pack/plugins/saved_objects_tagging/public/tags/tags_client.test.ts @@ -216,41 +216,83 @@ describe('TagsClient', () => { }); }); - ///// + describe('internal APIs', () => { + describe('#find', () => { + const findOptions: FindTagsOptions = { + search: 'for, you know.', + }; + let expectedTags: Tag[]; + + beforeEach(() => { + expectedTags = [ + createTag({ id: 'tag-1' }), + createTag({ id: 'tag-2' }), + createTag({ id: 'tag-3' }), + ]; + http.get.mockResolvedValue({ tags: expectedTags, total: expectedTags.length }); + }); - describe('#find', () => { - const findOptions: FindTagsOptions = { - search: 'for, you know.', - }; - let expectedTags: Tag[]; + it('calls `http.get` with the correct parameters', async () => { + await tagsClient.find(findOptions); - beforeEach(() => { - expectedTags = [ - createTag({ id: 'tag-1' }), - createTag({ id: 'tag-2' }), - createTag({ id: 'tag-3' }), - ]; - http.get.mockResolvedValue({ tags: expectedTags, total: expectedTags.length }); + expect(http.get).toHaveBeenCalledTimes(1); + expect(http.get).toHaveBeenCalledWith(`/internal/saved_objects_tagging/tags/_find`, { + query: findOptions, + }); + }); + it('returns the tag objects from the response', async () => { + const { tags, total } = await tagsClient.find(findOptions); + expect(tags).toEqual(expectedTags); + expect(total).toEqual(3); + }); + it('forwards the error from the http call if any', async () => { + const error = new Error('something when wrong'); + http.get.mockRejectedValue(error); + + await expect(tagsClient.find(findOptions)).rejects.toThrowError(error); + }); }); - it('calls `http.get` with the correct parameters', async () => { - await tagsClient.find(findOptions); + describe('#bulkDelete', () => { + const tagIds = ['id-to-delete-1', 'id-to-delete-2']; - expect(http.get).toHaveBeenCalledTimes(1); - expect(http.get).toHaveBeenCalledWith(`/internal/saved_objects_tagging/tags/_find`, { - query: findOptions, + beforeEach(() => { + http.post.mockResolvedValue({}); }); - }); - it('returns the tag objects from the response', async () => { - const { tags, total } = await tagsClient.find(findOptions); - expect(tags).toEqual(expectedTags); - expect(total).toEqual(3); - }); - it('forwards the error from the http call if any', async () => { - const error = new Error('something when wrong'); - http.get.mockRejectedValue(error); - await expect(tagsClient.find(findOptions)).rejects.toThrowError(error); + it('calls `http.post` with the correct parameters', async () => { + await tagsClient.bulkDelete(tagIds); + + expect(http.post).toHaveBeenCalledTimes(1); + expect(http.post).toHaveBeenCalledWith( + `/internal/saved_objects_tagging/tags/_bulk_delete`, + { + body: JSON.stringify({ + ids: tagIds, + }), + } + ); + }); + it('forwards the error from the http call if any', async () => { + const error = new Error('something when wrong'); + http.post.mockRejectedValue(error); + + await expect(tagsClient.bulkDelete(tagIds)).rejects.toThrowError(error); + }); + it('notifies its changeListener if the http call succeed', async () => { + await tagsClient.bulkDelete(tagIds); + + expect(changeListener.onDelete).toHaveBeenCalledTimes(2); + expect(changeListener.onDelete).toHaveBeenCalledWith(tagIds[0]); + expect(changeListener.onDelete).toHaveBeenCalledWith(tagIds[1]); + }); + it('ignores potential errors when calling `changeListener.onDelete`', async () => { + changeListener.onDelete.mockImplementation(() => { + throw new Error('error in onCreate'); + }); + + await expect(tagsClient.bulkDelete(tagIds)).resolves.toBeUndefined(); + }); }); }); }); diff --git a/x-pack/plugins/saved_objects_tagging/public/tags/tags_client.ts b/x-pack/plugins/saved_objects_tagging/public/tags/tags_client.ts index 3169babb2bae8..a866ae82f9702 100644 --- a/x-pack/plugins/saved_objects_tagging/public/tags/tags_client.ts +++ b/x-pack/plugins/saved_objects_tagging/public/tags/tags_client.ts @@ -34,6 +34,7 @@ const trapErrors = (fn: () => void) => { export interface ITagInternalClient extends ITagsClient { find(options: FindTagsOptions): Promise; + bulkDelete(ids: string[]): Promise; } export class TagsClient implements ITagInternalClient { @@ -114,4 +115,20 @@ export class TagsClient implements ITagInternalClient { }, }); } + + public async bulkDelete(tagIds: string[]) { + await this.http.post<{}>('/internal/saved_objects_tagging/tags/_bulk_delete', { + body: JSON.stringify({ + ids: tagIds, + }), + }); + + trapErrors(() => { + if (this.changeListener) { + tagIds.forEach((tagId) => { + this.changeListener!.onDelete(tagId); + }); + } + }); + } } diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/index.ts b/x-pack/plugins/saved_objects_tagging/server/routes/index.ts index 9519f54e01693..facfb3f690a28 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/index.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/index.ts @@ -10,7 +10,7 @@ import { registerDeleteTagRoute } from './delete_tag'; import { registerGetAllTagsRoute } from './get_all_tags'; import { registerGetTagRoute } from './get_tag'; import { registerUpdateTagRoute } from './update_tag'; -import { registerInternalFindTagsRoute } from './internal'; +import { registerInternalFindTagsRoute, registerInternalBulkDeleteRoute } from './internal'; export const registerRoutes = ({ router }: { router: IRouter }) => { // public API @@ -21,4 +21,5 @@ export const registerRoutes = ({ router }: { router: IRouter }) => { registerGetTagRoute(router); // internal API registerInternalFindTagsRoute(router); + registerInternalBulkDeleteRoute(router); }; diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/internal/bulk_delete.ts b/x-pack/plugins/saved_objects_tagging/server/routes/internal/bulk_delete.ts new file mode 100644 index 0000000000000..bade81678543d --- /dev/null +++ b/x-pack/plugins/saved_objects_tagging/server/routes/internal/bulk_delete.ts @@ -0,0 +1,33 @@ +/* + * 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 { schema } from '@kbn/config-schema'; +import { IRouter } from 'src/core/server'; + +export const registerInternalBulkDeleteRoute = (router: IRouter) => { + router.post( + { + path: '/internal/saved_objects_tagging/tags/_bulk_delete', + validate: { + body: schema.object({ + ids: schema.arrayOf(schema.string()), + }), + }, + }, + router.handleLegacyErrors(async (ctx, req, res) => { + const { ids: tagIds } = req.body; + const client = ctx.tags!.tagsClient; + + for (const tagId of tagIds) { + await client.delete(tagId); + } + + return res.ok({ + body: {}, + }); + }) + ); +}; diff --git a/x-pack/plugins/saved_objects_tagging/server/routes/internal/index.ts b/x-pack/plugins/saved_objects_tagging/server/routes/internal/index.ts index 9d427cfe5831c..e20403af1f59b 100644 --- a/x-pack/plugins/saved_objects_tagging/server/routes/internal/index.ts +++ b/x-pack/plugins/saved_objects_tagging/server/routes/internal/index.ts @@ -5,3 +5,4 @@ */ export { registerInternalFindTagsRoute } from './find_tags'; +export { registerInternalBulkDeleteRoute } from './bulk_delete'; diff --git a/x-pack/plugins/security_solution/common/license/license.ts b/x-pack/plugins/security_solution/common/license/license.ts new file mode 100644 index 0000000000000..96c1a14ceb1f4 --- /dev/null +++ b/x-pack/plugins/security_solution/common/license/license.ts @@ -0,0 +1,60 @@ +/* + * 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, Subscription } from 'rxjs'; +import { ILicense } from '../../../licensing/common/types'; + +// Generic license service class that works with the license observable +// Both server and client plugins instancates a singleton version of this class +export class LicenseService { + private observable: Observable | null = null; + private subscription: Subscription | null = null; + private licenseInformation: ILicense | null = null; + + private updateInformation(licenseInformation: ILicense) { + this.licenseInformation = licenseInformation; + } + + public start(license$: Observable) { + this.observable = license$; + this.subscription = this.observable.subscribe(this.updateInformation.bind(this)); + } + + public stop() { + if (this.subscription) { + this.subscription.unsubscribe(); + } + } + + public getLicenseInformation() { + return this.licenseInformation; + } + + public getLicenseInformation$() { + return this.observable; + } + + public isGoldPlus() { + return ( + this.licenseInformation?.isAvailable && + this.licenseInformation?.isActive && + this.licenseInformation?.hasAtLeast('gold') + ); + } + public isPlatinumPlus() { + return ( + this.licenseInformation?.isAvailable && + this.licenseInformation?.isActive && + this.licenseInformation?.hasAtLeast('platinum') + ); + } + public isEnterprise() { + return ( + this.licenseInformation?.isAvailable && + this.licenseInformation?.isActive && + this.licenseInformation?.hasAtLeast('enterprise') + ); + } +} diff --git a/x-pack/plugins/security_solution/public/common/hooks/use_license.ts b/x-pack/plugins/security_solution/public/common/hooks/use_license.ts new file mode 100644 index 0000000000000..db4d588bf293f --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/hooks/use_license.ts @@ -0,0 +1,13 @@ +/* + * 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 { LicenseService } from '../../../common/license/license'; + +export const licenseService = new LicenseService(); + +export function useLicense() { + return licenseService; +} diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx index abc9a2cbd027c..bfa592b1f9c8e 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx @@ -13,8 +13,20 @@ import { EndpointDocGenerator } from '../../../../../common/endpoint/generate_da import { AppContextTestRender, createAppRootMockRenderer } from '../../../../common/mock/endpoint'; import { getPolicyDetailPath, getEndpointListPath } from '../../../common/routing'; import { policyListApiPathHandlers } from '../store/policy_list/test_mock_utils'; +import { licenseService } from '../../../../common/hooks/use_license'; jest.mock('../../../../common/components/link_to'); +jest.mock('../../../../common/hooks/use_license', () => { + const licenseServiceInstance = { + isPlatinumPlus: jest.fn(), + }; + return { + licenseService: licenseServiceInstance, + useLicense: () => { + return licenseServiceInstance; + }, + }; +}); describe('Policy Details', () => { type FindReactWrapperResponse = ReturnType['find']>; @@ -275,5 +287,40 @@ describe('Policy Details', () => { }); }); }); + describe('when the subscription tier is platinum or higher', () => { + beforeEach(() => { + (licenseService.isPlatinumPlus as jest.Mock).mockReturnValue(true); + policyView = render(); + }); + + it('malware popup and message customization options are shown', () => { + // use query for finding stuff, if it doesn't find it, just returns null + const userNotificationCheckbox = policyView.find( + 'EuiCheckbox[data-test-subj="malwareUserNotificationCheckbox"]' + ); + const userNotificationCustomMessageTextArea = policyView.find( + 'EuiTextArea[data-test-subj="malwareUserNotificationCustomMessage"]' + ); + expect(userNotificationCheckbox).toHaveLength(1); + expect(userNotificationCustomMessageTextArea).toHaveLength(1); + }); + }); + describe('when the subscription tier is gold or lower', () => { + beforeEach(() => { + (licenseService.isPlatinumPlus as jest.Mock).mockReturnValue(false); + policyView = render(); + }); + + it('malware popup and message customization options are hidden', () => { + const userNotificationCheckbox = policyView.find( + 'EuiCheckbox[data-test-subj="malwareUserNotificationCheckbox"]' + ); + const userNotificationCustomMessageTextArea = policyView.find( + 'EuiTextArea[data-test-subj="malwareUserNotificationCustomMessage"]' + ); + expect(userNotificationCheckbox).toHaveLength(0); + expect(userNotificationCustomMessageTextArea).toHaveLength(0); + }); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/protections/malware.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/protections/malware.tsx index 7259b2ec19ee2..c72093552f551 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/protections/malware.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_forms/protections/malware.tsx @@ -30,6 +30,7 @@ import { policyConfig } from '../../../store/policy_details/selectors'; import { usePolicyDetailsSelector } from '../../policy_hooks'; import { LinkToApp } from '../../../../../../common/components/endpoint/link_to_app'; import { popupVersionsMap } from './popup_options_to_versions'; +import { useLicense } from '../../../../../../common/hooks/use_license'; const ProtectionRadioGroup = styled.div` display: flex; @@ -116,6 +117,7 @@ export const MalwareProtections = React.memo(() => { policyDetailsConfig && policyDetailsConfig.windows.popup.malware.enabled; const userNotificationMessage = policyDetailsConfig && policyDetailsConfig.windows.popup.malware.message; + const isPlatinumPlus = useLicense().isPlatinumPlus(); const radios: Immutable { ); })} - - - - - - - - {userNotificationSelected && ( + {isPlatinumPlus && ( + <> + + + + + + + + )} + {isPlatinumPlus && userNotificationSelected && ( <> @@ -256,6 +265,7 @@ export const MalwareProtections = React.memo(() => { value={userNotificationMessage} onChange={handleCustomUserNotification} fullWidth={true} + data-test-subj="malwareUserNotificationCustomMessage" /> )} @@ -263,6 +273,7 @@ export const MalwareProtections = React.memo(() => { ); }, [ radios, + isPlatinumPlus, handleUserNotificationCheckbox, userNotificationSelected, userNotificationMessage, diff --git a/x-pack/plugins/security_solution/public/plugin.tsx b/x-pack/plugins/security_solution/public/plugin.tsx index 5895880adb26a..5cc0d79a3f9a3 100644 --- a/x-pack/plugins/security_solution/public/plugin.tsx +++ b/x-pack/plugins/security_solution/public/plugin.tsx @@ -60,6 +60,7 @@ import { } from '../common/search_strategy/index_fields'; import { SecurityAppStore } from './common/store/store'; import { getCaseConnectorUI } from './common/lib/connectors'; +import { licenseService } from './common/hooks/use_license'; import { LazyEndpointPolicyEditExtension } from './management/pages/policy/view/ingest_manager_integration/lazy_endpoint_policy_edit_extension'; import { LazyEndpointPolicyCreateExtension } from './management/pages/policy/view/ingest_manager_integration/lazy_endpoint_policy_create_extension'; @@ -345,6 +346,7 @@ export class Plugin implements IPlugin; private manifestTask: ManifestTask | undefined; private exceptionsCache: LRU; @@ -364,6 +366,8 @@ export class Plugin implements IPlugin new MockUsageCollector(options), }, }; @@ -77,23 +77,23 @@ const getMockFetchContext = (mockedCallCluster: jest.Mock) => { describe('error handling', () => { it('handles a 404 when searching for space usage', async () => { - const { features, licensing, usageCollecion } = setup({ + const { features, licensing, usageCollection } = setup({ license: { isAvailable: true, type: 'basic' }, }); - const { fetch: getSpacesUsage } = getSpacesUsageCollector(usageCollecion as any, { + const collector = getSpacesUsageCollector(usageCollection as any, { kibanaIndexConfig$: Rx.of({ kibana: { index: '.kibana' } }), features, licensing, }); - await getSpacesUsage(getMockFetchContext(jest.fn().mockRejectedValue({ status: 404 }))); + await collector.fetch(getMockFetchContext(jest.fn().mockRejectedValue({ status: 404 }))); }); it('throws error for a non-404', async () => { - const { features, licensing, usageCollecion } = setup({ + const { features, licensing, usageCollection } = setup({ license: { isAvailable: true, type: 'basic' }, }); - const { fetch: getSpacesUsage } = getSpacesUsageCollector(usageCollecion as any, { + const collector = getSpacesUsageCollector(usageCollection as any, { kibanaIndexConfig$: Rx.of({ kibana: { index: '.kibana' } }), features, licensing, @@ -103,7 +103,7 @@ describe('error handling', () => { for (const statusCode of statusCodes) { const error = { status: statusCode }; await expect( - getSpacesUsage(getMockFetchContext(jest.fn().mockRejectedValue(error))) + collector.fetch(getMockFetchContext(jest.fn().mockRejectedValue(error))) ).rejects.toBe(error); } }); @@ -112,15 +112,15 @@ describe('error handling', () => { describe('with a basic license', () => { let usageStats: UsageStats; beforeAll(async () => { - const { features, licensing, usageCollecion } = setup({ + const { features, licensing, usageCollection } = setup({ license: { isAvailable: true, type: 'basic' }, }); - const { fetch: getSpacesUsage } = getSpacesUsageCollector(usageCollecion as any, { + const collector = getSpacesUsageCollector(usageCollection as any, { kibanaIndexConfig$: pluginInitializerContextConfigMock({}).legacy.globalConfig$, features, licensing, }); - usageStats = await getSpacesUsage(getMockFetchContext(defaultCallClusterMock)); + usageStats = await collector.fetch(getMockFetchContext(defaultCallClusterMock)); expect(defaultCallClusterMock).toHaveBeenCalledWith('search', { body: { @@ -162,13 +162,13 @@ describe('with a basic license', () => { describe('with no license', () => { let usageStats: UsageStats; beforeAll(async () => { - const { features, licensing, usageCollecion } = setup({ license: { isAvailable: false } }); - const { fetch: getSpacesUsage } = getSpacesUsageCollector(usageCollecion as any, { + const { features, licensing, usageCollection } = setup({ license: { isAvailable: false } }); + const collector = getSpacesUsageCollector(usageCollection as any, { kibanaIndexConfig$: pluginInitializerContextConfigMock({}).legacy.globalConfig$, features, licensing, }); - usageStats = await getSpacesUsage(getMockFetchContext(defaultCallClusterMock)); + usageStats = await collector.fetch(getMockFetchContext(defaultCallClusterMock)); }); test('sets enabled to false', () => { @@ -191,15 +191,15 @@ describe('with no license', () => { describe('with platinum license', () => { let usageStats: UsageStats; beforeAll(async () => { - const { features, licensing, usageCollecion } = setup({ + const { features, licensing, usageCollection } = setup({ license: { isAvailable: true, type: 'platinum' }, }); - const { fetch: getSpacesUsage } = getSpacesUsageCollector(usageCollecion as any, { + const collector = getSpacesUsageCollector(usageCollection as any, { kibanaIndexConfig$: pluginInitializerContextConfigMock({}).legacy.globalConfig$, features, licensing, }); - usageStats = await getSpacesUsage(getMockFetchContext(defaultCallClusterMock)); + usageStats = await collector.fetch(getMockFetchContext(defaultCallClusterMock)); }); test('sets enabled to true', () => { diff --git a/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/geo_threshold.ts b/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/geo_threshold.ts index fa7d38a6072fb..8247cc787d365 100644 --- a/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/geo_threshold.ts +++ b/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/geo_threshold.ts @@ -38,7 +38,7 @@ export function transformResults( return _.map(subBuckets, (subBucket) => { const locationFieldResult = _.get( subBucket, - `entityHits.hits.hits[0].fields.${geoField}[0]`, + `entityHits.hits.hits[0].fields["${geoField}"][0]`, '' ); const location = locationFieldResult @@ -50,7 +50,7 @@ export function transformResults( : null; const dateInShape = _.get( subBucket, - `entityHits.hits.hits[0].fields.${dateField}[0]`, + `entityHits.hits.hits[0].fields["${dateField}"][0]`, null ); const docId = _.get(subBucket, `entityHits.hits.hits[0]._id`); diff --git a/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/tests/es_sample_response.json b/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/tests/es_sample_response.json index 1281777c03761..70edbd09aa5a1 100644 --- a/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/tests/es_sample_response.json +++ b/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/tests/es_sample_response.json @@ -13,48 +13,7 @@ "relation" : "gte" }, "max_score" : 0.0, - "hits" : [ - { - "_index" : "flight_tracks", - "_id" : "XOng1XQB6yyY-xQxbwWM", - "_score" : 0.0, - "fields" : { - "@timestamp" : [ - "2020-09-28T18:01:29.580Z" - ] - } - }, - { - "_index" : "flight_tracks", - "_id" : "Xeng1XQB6yyY-xQxbwWM", - "_score" : 0.0, - "fields" : { - "@timestamp" : [ - "2020-09-28T18:01:29.580Z" - ] - } - }, - { - "_index" : "flight_tracks", - "_id" : "Xung1XQB6yyY-xQxbwWM", - "_score" : 0.0, - "fields" : { - "@timestamp" : [ - "2020-09-28T18:01:29.580Z" - ] - } - }, - { - "_index" : "flight_tracks", - "_id" : "UOjg1XQB6yyY-xQxZvMz", - "_score" : 0.0, - "fields" : { - "@timestamp" : [ - "2020-09-28T18:01:27.266Z" - ] - } - } - ] + "hits" : [] }, "aggregations" : { "shapes" : { diff --git a/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/tests/es_sample_response_with_nesting.json b/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/tests/es_sample_response_with_nesting.json new file mode 100644 index 0000000000000..a4b7b6872b341 --- /dev/null +++ b/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/tests/es_sample_response_with_nesting.json @@ -0,0 +1,170 @@ +{ + "took" : 2760, + "timed_out" : false, + "_shards" : { + "total" : 1, + "successful" : 1, + "skipped" : 0, + "failed" : 0 + }, + "hits" : { + "total" : { + "value" : 10000, + "relation" : "gte" + }, + "max_score" : 0.0, + "hits" : [] + }, + "aggregations" : { + "shapes" : { + "meta" : { }, + "buckets" : { + "0DrJu3QB6yyY-xQxv6Ip" : { + "doc_count" : 1047, + "entitySplit" : { + "doc_count_error_upper_bound" : 0, + "sum_other_doc_count" : 957, + "buckets" : [ + { + "key" : "936", + "doc_count" : 9, + "entityHits" : { + "hits" : { + "total" : { + "value" : 9, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "flight_tracks", + "_id" : "N-ng1XQB6yyY-xQxnGSM", + "_score" : null, + "fields" : { + "time_data.@timestamp" : [ + "2020-09-28T18:01:41.190Z" + ], + "geo.coords.location" : [ + "40.62806099653244, -82.8814151789993" + ], + "entity_id" : [ + "936" + ] + }, + "sort" : [ + 1601316101190 + ] + } + ] + } + } + }, + { + "key" : "AAL2019", + "doc_count" : 9, + "entityHits" : { + "hits" : { + "total" : { + "value" : 9, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "flight_tracks", + "_id" : "iOng1XQB6yyY-xQxnGSM", + "_score" : null, + "fields" : { + "time_data.@timestamp" : [ + "2020-09-28T18:01:41.191Z" + ], + "geo.coords.location" : [ + "39.006176185794175, -82.22068064846098" + ], + "entity_id" : [ + "AAL2019" + ] + }, + "sort" : [ + 1601316101191 + ] + } + ] + } + } + }, + { + "key" : "AAL2323", + "doc_count" : 9, + "entityHits" : { + "hits" : { + "total" : { + "value" : 9, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "flight_tracks", + "_id" : "n-ng1XQB6yyY-xQxnGSM", + "_score" : null, + "fields" : { + "time_data.@timestamp" : [ + "2020-09-28T18:01:41.191Z" + ], + "geo.coords.location" : [ + "41.6677269525826, -84.71324851736426" + ], + "entity_id" : [ + "AAL2323" + ] + }, + "sort" : [ + 1601316101191 + ] + } + ] + } + } + }, + { + "key" : "ABD5250", + "doc_count" : 9, + "entityHits" : { + "hits" : { + "total" : { + "value" : 9, + "relation" : "eq" + }, + "max_score" : null, + "hits" : [ + { + "_index" : "flight_tracks", + "_id" : "GOng1XQB6yyY-xQxnGWM", + "_score" : null, + "fields" : { + "time_data.@timestamp" : [ + "2020-09-28T18:01:41.192Z" + ], + "geo.coords.location" : [ + "39.07997465226799, 6.073727197945118" + ], + "entity_id" : [ + "ABD5250" + ] + }, + "sort" : [ + 1601316101192 + ] + } + ] + } + } + } + ] + } + } + } + } + } +} diff --git a/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/tests/geo_threshold.test.ts b/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/tests/geo_threshold.test.ts index 0aaf30ab2f3fb..e4cee9c677713 100644 --- a/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/tests/geo_threshold.test.ts +++ b/x-pack/plugins/stack_alerts/server/alert_types/geo_threshold/tests/geo_threshold.test.ts @@ -5,6 +5,7 @@ */ import sampleJsonResponse from './es_sample_response.json'; +import sampleJsonResponseWithNesting from './es_sample_response_with_nesting.json'; import { getMovedEntities, transformResults } from '../geo_threshold'; import { OTHER_CATEGORY } from '../es_query_builder'; import { SearchResponse } from 'elasticsearch'; @@ -51,6 +52,46 @@ describe('geo_threshold', () => { ]); }); + const nestedDateField = 'time_data.@timestamp'; + const nestedGeoField = 'geo.coords.location'; + it('should correctly transform expected results if fields are nested', async () => { + const transformedResults = transformResults( + (sampleJsonResponseWithNesting as unknown) as SearchResponse, + nestedDateField, + nestedGeoField + ); + expect(transformedResults).toEqual([ + { + dateInShape: '2020-09-28T18:01:41.190Z', + docId: 'N-ng1XQB6yyY-xQxnGSM', + entityName: '936', + location: [-82.8814151789993, 40.62806099653244], + shapeLocationId: '0DrJu3QB6yyY-xQxv6Ip', + }, + { + dateInShape: '2020-09-28T18:01:41.191Z', + docId: 'iOng1XQB6yyY-xQxnGSM', + entityName: 'AAL2019', + location: [-82.22068064846098, 39.006176185794175], + shapeLocationId: '0DrJu3QB6yyY-xQxv6Ip', + }, + { + dateInShape: '2020-09-28T18:01:41.191Z', + docId: 'n-ng1XQB6yyY-xQxnGSM', + entityName: 'AAL2323', + location: [-84.71324851736426, 41.6677269525826], + shapeLocationId: '0DrJu3QB6yyY-xQxv6Ip', + }, + { + dateInShape: '2020-09-28T18:01:41.192Z', + docId: 'GOng1XQB6yyY-xQxnGWM', + entityName: 'ABD5250', + location: [6.073727197945118, 39.07997465226799], + shapeLocationId: '0DrJu3QB6yyY-xQxv6Ip', + }, + ]); + }); + it('should return an empty array if no results', async () => { const transformedResults = transformResults(undefined, dateField, geoField); expect(transformedResults).toEqual([]); diff --git a/x-pack/plugins/vis_type_timeseries_enhanced/README.md b/x-pack/plugins/vis_type_timeseries_enhanced/README.md new file mode 100644 index 0000000000000..33aa16d8574ae --- /dev/null +++ b/x-pack/plugins/vis_type_timeseries_enhanced/README.md @@ -0,0 +1,10 @@ +# vis_type_timeseries_enhanced + +The `vis_type_timeseries_enhanced` plugin is the x-pack counterpart to the OSS `vis_type_timeseries` plugin. + +It exists to provide Elastic-licensed services, or parts of services, which +enhance existing OSS functionality from `vis_type_timeseries`. + +Currently the `vis_type_timeseries_enhanced` plugin doesn't return any APIs which you can +consume directly. + diff --git a/x-pack/plugins/vis_type_timeseries_enhanced/kibana.json b/x-pack/plugins/vis_type_timeseries_enhanced/kibana.json new file mode 100644 index 0000000000000..4b296856c3f97 --- /dev/null +++ b/x-pack/plugins/vis_type_timeseries_enhanced/kibana.json @@ -0,0 +1,10 @@ +{ + "id": "visTypeTimeseriesEnhanced", + "version": "8.0.0", + "kibanaVersion": "kibana", + "server": true, + "ui": false, + "requiredPlugins": [ + "visTypeTimeseries" + ] +} diff --git a/x-pack/plugins/vis_type_timeseries_enhanced/server/index.ts b/x-pack/plugins/vis_type_timeseries_enhanced/server/index.ts new file mode 100644 index 0000000000000..d2665ec1e2813 --- /dev/null +++ b/x-pack/plugins/vis_type_timeseries_enhanced/server/index.ts @@ -0,0 +1,11 @@ +/* + * 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 { VisTypeTimeseriesEnhanced } from './plugin'; + +export const plugin = (initializerContext: PluginInitializerContext) => + new VisTypeTimeseriesEnhanced(initializerContext); diff --git a/x-pack/plugins/vis_type_timeseries_enhanced/server/plugin.ts b/x-pack/plugins/vis_type_timeseries_enhanced/server/plugin.ts new file mode 100644 index 0000000000000..0598a691ab7c5 --- /dev/null +++ b/x-pack/plugins/vis_type_timeseries_enhanced/server/plugin.ts @@ -0,0 +1,33 @@ +/* + * 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 { Plugin, PluginInitializerContext, Logger, CoreSetup } from 'src/core/server'; +import { VisTypeTimeseriesSetup } from 'src/plugins/vis_type_timeseries/server'; +import { RollupSearchStrategy } from './search_strategies/rollup_search_strategy'; + +interface VisTypeTimeseriesEnhancedSetupDependencies { + visTypeTimeseries: VisTypeTimeseriesSetup; +} + +export class VisTypeTimeseriesEnhanced + implements Plugin { + private logger: Logger; + + constructor(initializerContext: PluginInitializerContext) { + this.logger = initializerContext.logger.get('vis_type_timeseries_enhanced'); + } + + public async setup( + core: CoreSetup, + { visTypeTimeseries }: VisTypeTimeseriesEnhancedSetupDependencies + ) { + this.logger.debug('Starting plugin'); + + visTypeTimeseries.addSearchStrategy(new RollupSearchStrategy()); + } + + public start() {} +} diff --git a/x-pack/plugins/rollup/server/lib/search_strategies/lib/interval_helper.test.js b/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/lib/interval_helper.test.ts similarity index 100% rename from x-pack/plugins/rollup/server/lib/search_strategies/lib/interval_helper.test.js rename to x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/lib/interval_helper.test.ts diff --git a/x-pack/plugins/rollup/server/lib/search_strategies/lib/interval_helper.ts b/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/lib/interval_helper.ts similarity index 100% rename from x-pack/plugins/rollup/server/lib/search_strategies/lib/interval_helper.ts rename to x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/lib/interval_helper.ts diff --git a/x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_capabilities.test.js b/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_capabilities.test.ts similarity index 77% rename from x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_capabilities.test.js rename to x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_capabilities.test.ts index 977601247594f..6c30895635fe5 100644 --- a/x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_capabilities.test.js +++ b/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_capabilities.test.ts @@ -3,27 +3,21 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { getRollupSearchCapabilities } from './rollup_search_capabilities'; +import { Unit } from '@elastic/datemath'; +import { RollupSearchCapabilities } from './rollup_search_capabilities'; -class DefaultSearchCapabilities { - constructor(request, fieldsCapabilities = {}) { - this.fieldsCapabilities = fieldsCapabilities; - this.parseInterval = jest.fn((interval) => interval); - } -} +import { ReqFacade, VisPayload } from '../../../../../src/plugins/vis_type_timeseries/server'; describe('Rollup Search Capabilities', () => { const testTimeZone = 'time_zone'; const testInterval = '10s'; const rollupIndex = 'rollupIndex'; - const request = {}; + const request = ({} as unknown) as ReqFacade; - let RollupSearchCapabilities; - let fieldsCapabilities; - let rollupSearchCaps; + let fieldsCapabilities: Record; + let rollupSearchCaps: RollupSearchCapabilities; beforeEach(() => { - RollupSearchCapabilities = getRollupSearchCapabilities(DefaultSearchCapabilities); fieldsCapabilities = { [rollupIndex]: { aggs: { @@ -41,7 +35,6 @@ describe('Rollup Search Capabilities', () => { }); test('should create instance of RollupSearchRequest', () => { - expect(rollupSearchCaps).toBeInstanceOf(DefaultSearchCapabilities); expect(rollupSearchCaps.fieldsCapabilities).toBe(fieldsCapabilities); expect(rollupSearchCaps.rollupIndex).toBe(rollupIndex); }); @@ -55,9 +48,9 @@ describe('Rollup Search Capabilities', () => { }); describe('getValidTimeInterval', () => { - let rollupJobInterval; - let userInterval; - let getSuitableUnit; + let rollupJobInterval: { value: number; unit: Unit }; + let userInterval: { value: number; unit: Unit }; + let getSuitableUnit: Unit; beforeEach(() => { rollupSearchCaps.parseInterval = jest @@ -81,7 +74,7 @@ describe('Rollup Search Capabilities', () => { getSuitableUnit = 'd'; - expect(rollupSearchCaps.getValidTimeInterval()).toBe('1d'); + expect(rollupSearchCaps.getValidTimeInterval('')).toBe('1d'); }); test('should return 1w as common interval for 7d(user interval) and 1d(rollup interval) - calendar intervals', () => { @@ -96,7 +89,7 @@ describe('Rollup Search Capabilities', () => { getSuitableUnit = 'w'; - expect(rollupSearchCaps.getValidTimeInterval()).toBe('1w'); + expect(rollupSearchCaps.getValidTimeInterval('')).toBe('1w'); }); test('should return 1w as common interval for 1d(user interval) and 1w(rollup interval) - calendar intervals', () => { @@ -111,7 +104,7 @@ describe('Rollup Search Capabilities', () => { getSuitableUnit = 'w'; - expect(rollupSearchCaps.getValidTimeInterval()).toBe('1w'); + expect(rollupSearchCaps.getValidTimeInterval('')).toBe('1w'); }); test('should return 2y as common interval for 0.1y(user interval) and 2y(rollup interval) - fixed intervals', () => { @@ -124,7 +117,7 @@ describe('Rollup Search Capabilities', () => { unit: 'y', }; - expect(rollupSearchCaps.getValidTimeInterval()).toBe('2y'); + expect(rollupSearchCaps.getValidTimeInterval('')).toBe('2y'); }); test('should return 3h as common interval for 2h(user interval) and 3h(rollup interval) - fixed intervals', () => { @@ -137,7 +130,7 @@ describe('Rollup Search Capabilities', () => { unit: 'h', }; - expect(rollupSearchCaps.getValidTimeInterval()).toBe('3h'); + expect(rollupSearchCaps.getValidTimeInterval('')).toBe('3h'); }); test('should return 6m as common interval for 4m(user interval) and 3m(rollup interval) - fixed intervals', () => { @@ -150,7 +143,7 @@ describe('Rollup Search Capabilities', () => { unit: 'm', }; - expect(rollupSearchCaps.getValidTimeInterval()).toBe('6m'); + expect(rollupSearchCaps.getValidTimeInterval('')).toBe('6m'); }); }); }); diff --git a/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_capabilities.ts b/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_capabilities.ts new file mode 100644 index 0000000000000..015a371bd2a35 --- /dev/null +++ b/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_capabilities.ts @@ -0,0 +1,123 @@ +/* + * 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, has } from 'lodash'; +import { leastCommonInterval, isCalendarInterval } from './lib/interval_helper'; + +import { + ReqFacade, + DefaultSearchCapabilities, + VisPayload, +} from '../../../../../src/plugins/vis_type_timeseries/server'; + +export class RollupSearchCapabilities extends DefaultSearchCapabilities { + rollupIndex: string; + availableMetrics: Record; + + constructor( + req: ReqFacade, + fieldsCapabilities: Record, + rollupIndex: string + ) { + super(req, fieldsCapabilities); + + this.rollupIndex = rollupIndex; + this.availableMetrics = get(fieldsCapabilities, `${rollupIndex}.aggs`, {}); + } + + public get dateHistogram() { + const [dateHistogram] = Object.values(this.availableMetrics.date_histogram); + + return dateHistogram; + } + + public get defaultTimeInterval() { + return ( + this.dateHistogram.fixed_interval || + this.dateHistogram.calendar_interval || + /* + Deprecation: [interval] on [date_histogram] is deprecated, use [fixed_interval] or [calendar_interval] in the future. + We can remove the following line only for versions > 8.x + */ + this.dateHistogram.interval || + null + ); + } + + public get searchTimezone() { + return get(this.dateHistogram, 'time_zone', null); + } + + public get whiteListedMetrics() { + const baseRestrictions = this.createUiRestriction({ + count: this.createUiRestriction(), + }); + + const getFields = (fields: { [key: string]: any }) => + Object.keys(fields).reduce( + (acc, item) => ({ + ...acc, + [item]: true, + }), + this.createUiRestriction({}) + ); + + return Object.keys(this.availableMetrics).reduce( + (acc, item) => ({ + ...acc, + [item]: getFields(this.availableMetrics[item]), + }), + baseRestrictions + ); + } + + public get whiteListedGroupByFields() { + return this.createUiRestriction({ + everything: true, + terms: has(this.availableMetrics, 'terms'), + }); + } + + public get whiteListedTimerangeModes() { + return this.createUiRestriction({ + last_value: true, + }); + } + + getValidTimeInterval(userIntervalString: string) { + const parsedRollupJobInterval = this.parseInterval(this.defaultTimeInterval); + const inRollupJobUnit = this.convertIntervalToUnit( + userIntervalString, + parsedRollupJobInterval!.unit + ); + + const getValidCalendarInterval = () => { + let unit = parsedRollupJobInterval!.unit; + + if (inRollupJobUnit!.value > parsedRollupJobInterval!.value) { + const inSeconds = this.convertIntervalToUnit(userIntervalString, 's'); + if (inSeconds?.value) { + unit = this.getSuitableUnit(inSeconds.value); + } + } + + return { + value: 1, + unit, + }; + }; + + const getValidFixedInterval = () => ({ + value: leastCommonInterval(inRollupJobUnit?.value, parsedRollupJobInterval?.value), + unit: parsedRollupJobInterval!.unit, + }); + + const { value, unit } = (isCalendarInterval(parsedRollupJobInterval!) + ? getValidCalendarInterval + : getValidFixedInterval)(); + + return `${value}${unit}`; + } +} diff --git a/x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_strategy.test.js b/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_strategy.test.ts similarity index 56% rename from x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_strategy.test.js rename to x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_strategy.test.ts index f3da7ed3fdd17..ec6c91b616f5b 100644 --- a/x-pack/plugins/rollup/server/lib/search_strategies/rollup_search_strategy.test.js +++ b/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_strategy.test.ts @@ -3,15 +3,35 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { getRollupSearchStrategy } from './rollup_search_strategy'; +import { RollupSearchStrategy } from './rollup_search_strategy'; +import type { ReqFacade, VisPayload } from '../../../../../src/plugins/vis_type_timeseries/server'; + +jest.mock('../../../../../src/plugins/vis_type_timeseries/server', () => { + const actual = jest.requireActual('../../../../../src/plugins/vis_type_timeseries/server'); + class AbstractSearchStrategyMock { + getFieldsForWildcard() { + return [ + { + name: 'day_of_week.terms.value', + type: 'object', + esTypes: ['object'], + searchable: false, + aggregatable: false, + }, + ]; + } + } + + return { + ...actual, + AbstractSearchStrategy: AbstractSearchStrategyMock, + }; +}); describe('Rollup Search Strategy', () => { - let RollupSearchStrategy; - let RollupSearchCapabilities; - let callWithRequest; - let rollupResolvedData; + let rollupResolvedData: Promise; - const request = { + const request = ({ requestContext: { core: { elasticsearch: { @@ -25,41 +45,9 @@ describe('Rollup Search Strategy', () => { }, }, }, - }; - const getRollupService = jest.fn().mockImplementation(() => { - return { - callAsCurrentUser: async () => { - return rollupResolvedData; - }, - }; - }); - const indexPattern = 'indexPattern'; + } as unknown) as ReqFacade; - beforeEach(() => { - class AbstractSearchStrategy { - getCallWithRequestInstance = jest.fn(() => callWithRequest); - - getFieldsForWildcard() { - return [ - { - name: 'day_of_week.terms.value', - type: 'object', - esTypes: ['object'], - searchable: false, - aggregatable: false, - }, - ]; - } - } - - RollupSearchCapabilities = jest.fn(() => 'capabilities'); - - RollupSearchStrategy = getRollupSearchStrategy( - AbstractSearchStrategy, - RollupSearchCapabilities, - getRollupService - ); - }); + const indexPattern = 'indexPattern'; test('should create instance of RollupSearchRequest', () => { const rollupSearchStrategy = new RollupSearchStrategy(); @@ -68,68 +56,66 @@ describe('Rollup Search Strategy', () => { }); describe('checkForViability', () => { - let rollupSearchStrategy; + let rollupSearchStrategy: RollupSearchStrategy; const rollupIndex = 'rollupIndex'; beforeEach(() => { rollupSearchStrategy = new RollupSearchStrategy(); - rollupSearchStrategy.getRollupData = jest.fn(() => ({ - [rollupIndex]: { - rollup_jobs: [ - { - job_id: 'test', - rollup_index: rollupIndex, - index_pattern: 'kibana*', - fields: { - order_date: [ - { - agg: 'date_histogram', - delay: '1m', - interval: '1m', - time_zone: 'UTC', - }, - ], - day_of_week: [ - { - agg: 'terms', - }, - ], + rollupSearchStrategy.getRollupData = jest.fn(() => + Promise.resolve({ + [rollupIndex]: { + rollup_jobs: [ + { + job_id: 'test', + rollup_index: rollupIndex, + index_pattern: 'kibana*', + fields: { + order_date: [ + { + agg: 'date_histogram', + delay: '1m', + interval: '1m', + time_zone: 'UTC', + }, + ], + day_of_week: [ + { + agg: 'terms', + }, + ], + }, }, - }, - ], - }, - })); + ], + }, + }) + ); }); test('isViable should be false for invalid index', async () => { - const result = await rollupSearchStrategy.checkForViability(request, null); + const result = await rollupSearchStrategy.checkForViability( + request, + (null as unknown) as string + ); expect(result).toEqual({ isViable: false, capabilities: null, }); }); - - test('should get RollupSearchCapabilities for valid rollup index ', async () => { - await rollupSearchStrategy.checkForViability(request, rollupIndex); - - expect(RollupSearchCapabilities).toHaveBeenCalled(); - }); }); describe('getRollupData', () => { - let rollupSearchStrategy; + let rollupSearchStrategy: RollupSearchStrategy; beforeEach(() => { rollupSearchStrategy = new RollupSearchStrategy(); }); test('should return rollup data', async () => { - rollupResolvedData = Promise.resolve('data'); + rollupResolvedData = Promise.resolve({ body: 'data' }); const rollupData = await rollupSearchStrategy.getRollupData(request, indexPattern); - expect(getRollupService).toHaveBeenCalled(); expect(rollupData).toBe('data'); }); @@ -143,8 +129,8 @@ describe('Rollup Search Strategy', () => { }); describe('getFieldsForWildcard', () => { - let rollupSearchStrategy; - let fieldsCapabilities; + let rollupSearchStrategy: RollupSearchStrategy; + let fieldsCapabilities: Record; const rollupIndex = 'rollupIndex'; diff --git a/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_strategy.ts b/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_strategy.ts new file mode 100644 index 0000000000000..f1c20c318d109 --- /dev/null +++ b/x-pack/plugins/vis_type_timeseries_enhanced/server/search_strategies/rollup_search_strategy.ts @@ -0,0 +1,79 @@ +/* + * 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 { keyBy, isString } from 'lodash'; +import { + AbstractSearchStrategy, + ReqFacade, + VisPayload, +} from '../../../../../src/plugins/vis_type_timeseries/server'; + +import { + mergeCapabilitiesWithFields, + getCapabilitiesForRollupIndices, +} from '../../../../../src/plugins/data/server'; + +import { RollupSearchCapabilities } from './rollup_search_capabilities'; + +const getRollupIndices = (rollupData: { [key: string]: any }) => Object.keys(rollupData); +const isIndexPatternContainsWildcard = (indexPattern: string) => indexPattern.includes('*'); +const isIndexPatternValid = (indexPattern: string) => + indexPattern && isString(indexPattern) && !isIndexPatternContainsWildcard(indexPattern); + +export class RollupSearchStrategy extends AbstractSearchStrategy { + name = 'rollup'; + + async search(req: ReqFacade, bodies: any[]) { + return super.search(req, bodies, 'rollup'); + } + + async getRollupData(req: ReqFacade, indexPattern: string) { + return req.requestContext.core.elasticsearch.client.asCurrentUser.rollup + .getRollupIndexCaps({ + index: indexPattern, + }) + .then((data) => data.body) + .catch(() => Promise.resolve({})); + } + + async checkForViability(req: ReqFacade, indexPattern: string) { + let isViable = false; + let capabilities = null; + + if (isIndexPatternValid(indexPattern)) { + const rollupData = await this.getRollupData(req, indexPattern); + const rollupIndices = getRollupIndices(rollupData); + + isViable = rollupIndices.length === 1; + + if (isViable) { + const [rollupIndex] = rollupIndices; + const fieldsCapabilities = getCapabilitiesForRollupIndices(rollupData); + + capabilities = new RollupSearchCapabilities(req, fieldsCapabilities, rollupIndex); + } + } + + return { + isViable, + capabilities, + }; + } + + async getFieldsForWildcard( + req: ReqFacade, + indexPattern: string, + { + fieldsCapabilities, + rollupIndex, + }: { fieldsCapabilities: { [key: string]: any }; rollupIndex: string } + ) { + const fields = await super.getFieldsForWildcard(req, indexPattern); + const fieldsFromFieldCapsApi = keyBy(fields, 'name'); + const rollupIndexCapabilities = fieldsCapabilities[rollupIndex].aggs; + + return mergeCapabilitiesWithFields(rollupIndexCapabilities, fieldsFromFieldCapsApi); + } +} diff --git a/x-pack/test/functional/page_objects/tag_management_page.ts b/x-pack/test/functional/page_objects/tag_management_page.ts index 8b354e9d0e1c4..7d40bf5600da4 100644 --- a/x-pack/test/functional/page_objects/tag_management_page.ts +++ b/x-pack/test/functional/page_objects/tag_management_page.ts @@ -156,6 +156,13 @@ export function TagManagementPageProvider({ getService, getPageObjects }: FtrPro } } + /** + * Tag management page object. + * + * @remarks All the table manipulation helpers makes the assumption + * that all tags are displayed on a single page. Pagination + * and finding / interacting with a tag on another page is not supported. + */ class TagManagementPage { public readonly tagModal = new TagModal(this); @@ -272,6 +279,90 @@ export function TagManagementPageProvider({ getService, getPageObjects }: FtrPro await connectionLink.click(); } + /** + * Return true if the selection column is displayed on the table, false otherwise. + */ + async isSelectionColumnDisplayed() { + const firstRow = await testSubjects.find('tagsTableRow'); + const checkbox = await firstRow.findAllByCssSelector( + '.euiTableRowCellCheckbox .euiCheckbox__input' + ); + return Boolean(checkbox.length); + } + + /** + * Click on the selection checkbox of the tag matching given tag name. + */ + async selectTagByName(tagName: string) { + const tagRow = await this.getRowByName(tagName); + const checkbox = await tagRow.findByCssSelector( + '.euiTableRowCellCheckbox .euiCheckbox__input' + ); + await checkbox.click(); + } + + /** + * Returns true if the tag bulk action menu is displayed, false otherwise. + */ + async isActionMenuButtonDisplayed() { + return testSubjects.exists('actionBar-contextMenuButton'); + } + + /** + * Open the bulk action menu if not already opened. + */ + async openActionMenu() { + if (!(await this.isActionMenuOpened())) { + await this.toggleActionMenu(); + } + } + + /** + * Check if the action for given `actionId` is present in the bulk action menu. + * + * The menu will automatically be opened if not already, but the test must still + * select tags to make the action menu button appear. + */ + async isActionPresent(actionId: string) { + if (!(await this.isActionMenuButtonDisplayed())) { + return false; + } + const menuWasOpened = await this.isActionMenuOpened(); + if (!menuWasOpened) { + await this.openActionMenu(); + } + + const actionExists = await testSubjects.exists(`actionBar-button-${actionId}`); + + if (!menuWasOpened) { + await this.toggleActionMenu(); + } + + return actionExists; + } + + /** + * Click on given bulk action button + */ + async clickOnAction(actionId: string) { + await this.openActionMenu(); + await testSubjects.click(`actionBar-button-${actionId}`); + } + + /** + * Toggle (close if opened, open if closed) the bulk action menu. + */ + async toggleActionMenu() { + await testSubjects.click('actionBar-contextMenuButton'); + } + + /** + * Return true if the bulk action menu is opened, false otherwise. + */ + async isActionMenuOpened() { + return testSubjects.exists('actionBar-contextMenuPopover'); + } + /** * Return the info of all the tags currently displayed in the table (in table's order) */ diff --git a/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/apis/_bulk_delete.ts b/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/apis/_bulk_delete.ts new file mode 100644 index 0000000000000..0c9a06bd58828 --- /dev/null +++ b/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/apis/_bulk_delete.ts @@ -0,0 +1,87 @@ +/* + * 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 expect from '@kbn/expect'; +import { USERS, User, ExpectedResponse } from '../../../common/lib'; +import { FtrProviderContext } from '../services'; + +// eslint-disable-next-line import/no-default-export +export default function ({ getService }: FtrProviderContext) { + const esArchiver = getService('esArchiver'); + const supertest = getService('supertestWithoutAuth'); + + describe('POST /internal/saved_objects_tagging/tags/_bulk_delete', () => { + beforeEach(async () => { + await esArchiver.load('rbac_tags'); + }); + + afterEach(async () => { + await esArchiver.unload('rbac_tags'); + }); + + const responses: Record = { + authorized: { + httpCode: 200, + expectResponse: ({ body }) => { + expect(body).to.eql({}); + }, + }, + unauthorized: { + httpCode: 403, + expectResponse: ({ body }) => { + expect(body).to.eql({ + statusCode: 403, + error: 'Forbidden', + message: 'Unable to delete tag', + }); + }, + }, + }; + + const expectedResults: Record = { + authorized: [ + USERS.SUPERUSER, + USERS.DEFAULT_SPACE_SO_MANAGEMENT_WRITE_USER, + USERS.DEFAULT_SPACE_SO_TAGGING_WRITE_USER, + ], + unauthorized: [ + USERS.DEFAULT_SPACE_READ_USER, + USERS.DEFAULT_SPACE_SO_TAGGING_READ_USER, + USERS.DEFAULT_SPACE_DASHBOARD_READ_USER, + USERS.DEFAULT_SPACE_VISUALIZE_READ_USER, + USERS.DEFAULT_SPACE_ADVANCED_SETTINGS_READ_USER, + USERS.NOT_A_KIBANA_USER, + ], + }; + + const createUserTest = ( + { username, password, description }: User, + { httpCode, expectResponse }: ExpectedResponse + ) => { + it(`returns expected ${httpCode} response for ${description ?? username}`, async () => { + await supertest + .post(`/internal/saved_objects_tagging/tags/_bulk_delete`) + .send({ + ids: ['default-space-tag-1', 'default-space-tag-2'], + }) + .auth(username, password) + .expect(httpCode) + .then(expectResponse); + }); + }; + + const createTestSuite = () => { + Object.entries(expectedResults).forEach(([responseId, users]) => { + const response: ExpectedResponse = responses[responseId]; + users.forEach((user) => { + createUserTest(user, response); + }); + }); + }; + + createTestSuite(); + }); +} diff --git a/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/apis/index.ts b/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/apis/index.ts index 5f3d1cf854f82..727479546431c 100644 --- a/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/apis/index.ts +++ b/x-pack/test/saved_object_tagging/api_integration/security_and_spaces/apis/index.ts @@ -22,5 +22,6 @@ export default function ({ getService, loadTestFile }: FtrProviderContext) { loadTestFile(require.resolve('./update')); loadTestFile(require.resolve('./delete')); loadTestFile(require.resolve('./_find')); + loadTestFile(require.resolve('./_bulk_delete')); }); } diff --git a/x-pack/test/saved_object_tagging/functional/tests/bulk_actions.ts b/x-pack/test/saved_object_tagging/functional/tests/bulk_actions.ts new file mode 100644 index 0000000000000..556130bed7931 --- /dev/null +++ b/x-pack/test/saved_object_tagging/functional/tests/bulk_actions.ts @@ -0,0 +1,54 @@ +/* + * 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 expect from '@kbn/expect'; +import { FtrProviderContext } from '../ftr_provider_context'; + +// eslint-disable-next-line import/no-default-export +export default function ({ getPageObjects, getService }: FtrProviderContext) { + const esArchiver = getService('esArchiver'); + const PageObjects = getPageObjects(['common', 'security', 'savedObjects', 'tagManagement']); + const tagManagementPage = PageObjects.tagManagement; + + describe('table bulk actions', () => { + beforeEach(async () => { + await esArchiver.load('functional_base'); + await tagManagementPage.navigateTo(); + }); + afterEach(async () => { + await esArchiver.unload('functional_base'); + }); + + describe('bulk delete', () => { + it('deletes multiple tags', async () => { + await tagManagementPage.selectTagByName('tag-1'); + await tagManagementPage.selectTagByName('tag-3'); + + await tagManagementPage.clickOnAction('delete'); + + await PageObjects.common.clickConfirmOnModal(); + await tagManagementPage.waitUntilTableIsLoaded(); + + const displayedTags = await tagManagementPage.getDisplayedTagNames(); + expect(displayedTags.length).to.be(3); + expect(displayedTags).to.eql(['my-favorite-tag', 'tag with whitespace', 'tag-2']); + }); + }); + + describe('clear selection', () => { + it('clears the current selection', async () => { + await tagManagementPage.selectTagByName('tag-1'); + await tagManagementPage.selectTagByName('tag-3'); + + await tagManagementPage.clickOnAction('clear_selection'); + + await tagManagementPage.waitUntilTableIsLoaded(); + + expect(await tagManagementPage.isActionMenuButtonDisplayed()).to.be(false); + }); + }); + }); +} diff --git a/x-pack/test/saved_object_tagging/functional/tests/dashboard_integration.ts b/x-pack/test/saved_object_tagging/functional/tests/dashboard_integration.ts index 081fa1feb1c33..42ef8de2eb0c2 100644 --- a/x-pack/test/saved_object_tagging/functional/tests/dashboard_integration.ts +++ b/x-pack/test/saved_object_tagging/functional/tests/dashboard_integration.ts @@ -13,7 +13,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const listingTable = getService('listingTable'); const testSubjects = getService('testSubjects'); const find = getService('find'); - const PageObjects = getPageObjects(['dashboard', 'tagManagement', 'common']); + const PageObjects = getPageObjects(['dashboard', 'tagManagement', 'common', 'header']); /** * Select tags in the searchbar's tag filter. @@ -31,6 +31,8 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { // click elsewhere to close the filter dropdown const searchFilter = await find.byCssSelector('main .euiFieldSearch'); await searchFilter.click(); + // wait until the table refreshes + await listingTable.waitUntilTableIsLoaded(); }; describe('dashboard integration', () => { @@ -47,6 +49,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { beforeEach(async () => { await PageObjects.common.navigateToApp('dashboard'); await PageObjects.dashboard.gotoDashboardLandingPage(); + await listingTable.waitUntilTableIsLoaded(); }); it('allows to manually type tag filter query', async () => { @@ -96,6 +99,8 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); await PageObjects.dashboard.gotoDashboardLandingPage(); + await listingTable.waitUntilTableIsLoaded(); + await selectFilterTags('tag-1'); const itemNames = await listingTable.getAllItemsNames(); expect(itemNames).to.contain('my-new-dashboard'); @@ -128,8 +133,11 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { expect(await tagModal.isOpened()).to.be(false); await PageObjects.dashboard.clickSave(); + await PageObjects.common.waitForSaveModalToClose(); await PageObjects.dashboard.gotoDashboardLandingPage(); + await listingTable.waitUntilTableIsLoaded(); + await selectFilterTags('my-new-tag'); const itemNames = await listingTable.getAllItemsNames(); expect(itemNames).to.contain('dashboard-with-new-tag'); @@ -140,6 +148,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { beforeEach(async () => { await PageObjects.common.navigateToApp('dashboard'); await PageObjects.dashboard.gotoDashboardLandingPage(); + await listingTable.waitUntilTableIsLoaded(); }); it('allows to select tags for an existing dashboard', async () => { @@ -152,6 +161,8 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); await PageObjects.dashboard.gotoDashboardLandingPage(); + await listingTable.waitUntilTableIsLoaded(); + await selectFilterTags('tag-3'); const itemNames = await listingTable.getAllItemsNames(); expect(itemNames).to.contain('dashboard 4 with real data (tag-1)'); diff --git a/x-pack/test/saved_object_tagging/functional/tests/feature_control.ts b/x-pack/test/saved_object_tagging/functional/tests/feature_control.ts index 72beabca59f5c..65443fb517edf 100644 --- a/x-pack/test/saved_object_tagging/functional/tests/feature_control.ts +++ b/x-pack/test/saved_object_tagging/functional/tests/feature_control.ts @@ -35,6 +35,13 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); }; + const selectSomeTags = async () => { + if (await tagManagementPage.isSelectionColumnDisplayed()) { + await tagManagementPage.selectTagByName('tag-1'); + await tagManagementPage.selectTagByName('tag-3'); + } + }; + const addFeatureControlSuite = ({ user, description, privileges }: FeatureControlUserSuite) => { const testPrefix = (allowed: boolean) => (allowed ? `can` : `can't`); @@ -57,6 +64,11 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { expect(await tagManagementPage.isDeleteButtonVisible()).to.be(privileges.delete); }); + it(`${testPrefix(privileges.delete)} bulk delete tags`, async () => { + await selectSomeTags(); + expect(await tagManagementPage.isActionPresent('delete')).to.be(privileges.delete); + }); + it(`${testPrefix(privileges.create)} create tag`, async () => { expect(await tagManagementPage.isCreateButtonVisible()).to.be(privileges.create); }); diff --git a/x-pack/test/saved_object_tagging/functional/tests/index.ts b/x-pack/test/saved_object_tagging/functional/tests/index.ts index 0ddfa64d682a8..7fd0605c34d76 100644 --- a/x-pack/test/saved_object_tagging/functional/tests/index.ts +++ b/x-pack/test/saved_object_tagging/functional/tests/index.ts @@ -17,6 +17,7 @@ export default function ({ loadTestFile, getService }: FtrProviderContext) { }); loadTestFile(require.resolve('./listing')); + loadTestFile(require.resolve('./bulk_actions')); loadTestFile(require.resolve('./create')); loadTestFile(require.resolve('./edit')); loadTestFile(require.resolve('./som_integration')); diff --git a/x-pack/test/saved_object_tagging/functional/tests/visualize_integration.ts b/x-pack/test/saved_object_tagging/functional/tests/visualize_integration.ts index d8bd39ac7dc53..834c3083071df 100644 --- a/x-pack/test/saved_object_tagging/functional/tests/visualize_integration.ts +++ b/x-pack/test/saved_object_tagging/functional/tests/visualize_integration.ts @@ -13,7 +13,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const listingTable = getService('listingTable'); const testSubjects = getService('testSubjects'); const find = getService('find'); - const PageObjects = getPageObjects(['visualize', 'tagManagement', 'visEditor']); + const PageObjects = getPageObjects(['visualize', 'tagManagement', 'visEditor', 'common']); /** * Select tags in the searchbar's tag filter. @@ -31,6 +31,8 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { // click elsewhere to close the filter dropdown const searchFilter = await find.byCssSelector('main .euiFieldSearch'); await searchFilter.click(); + // wait until the table refreshes + await listingTable.waitUntilTableIsLoaded(); }; const selectSavedObjectTags = async (...tagNames: string[]) => { @@ -56,6 +58,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { describe('listing', () => { beforeEach(async () => { await PageObjects.visualize.gotoVisualizationLandingPage(); + await listingTable.waitUntilTableIsLoaded(); }); it('allows to manually type tag filter query', async () => { @@ -83,7 +86,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); describe('creating', () => { - it.skip('allows to assign tags to the new visualization', async () => { + it('allows to assign tags to the new visualization', async () => { await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickMarkdownWidget(); @@ -95,14 +98,17 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await selectSavedObjectTags('tag-1'); await testSubjects.click('confirmSaveSavedObjectButton'); + await PageObjects.common.waitForSaveModalToClose(); + await PageObjects.visualize.gotoVisualizationLandingPage(); + await listingTable.waitUntilTableIsLoaded(); await selectFilterTags('tag-1'); const itemNames = await listingTable.getAllItemsNames(); expect(itemNames).to.contain('My new markdown viz'); }); - it('allows to assign tags to the new visualization', async () => { + it('allows to create a tag from the tag selector', async () => { const { tagModal } = PageObjects.tagManagement; await PageObjects.visualize.navigateToNewVisualization(); @@ -133,7 +139,10 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { expect(await tagModal.isOpened()).to.be(false); await testSubjects.click('confirmSaveSavedObjectButton'); + await PageObjects.common.waitForSaveModalToClose(); + await PageObjects.visualize.gotoVisualizationLandingPage(); + await listingTable.waitUntilTableIsLoaded(); await selectFilterTags('my-new-tag'); const itemNames = await listingTable.getAllItemsNames(); @@ -144,6 +153,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { describe('editing', () => { beforeEach(async () => { await PageObjects.visualize.gotoVisualizationLandingPage(); + await listingTable.waitUntilTableIsLoaded(); }); it('allows to assign tags to an existing visualization', async () => { @@ -153,7 +163,10 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await selectSavedObjectTags('tag-2'); await testSubjects.click('confirmSaveSavedObjectButton'); + await PageObjects.common.waitForSaveModalToClose(); + await PageObjects.visualize.gotoVisualizationLandingPage(); + await listingTable.waitUntilTableIsLoaded(); await selectFilterTags('tag-2'); const itemNames = await listingTable.getAllItemsNames(); diff --git a/yarn.lock b/yarn.lock index f2b4147fc3c9b..3bfa72cc50aeb 100644 --- a/yarn.lock +++ b/yarn.lock @@ -9367,10 +9367,10 @@ chrome-trace-event@^1.0.2: dependencies: tslib "^1.9.0" -chromedriver@^86.0.0: - version "86.0.0" - resolved "https://registry.yarnpkg.com/chromedriver/-/chromedriver-86.0.0.tgz#4b9504d5bbbcd4c6bd6d6fd1dd8247ab8cdeca67" - integrity sha512-byLJWhAfuYOmzRYPDf4asJgGDbI4gJGHa+i8dnQZGuv+6WW1nW1Fg+8zbBMOfLvGn7sKL41kVdmCEVpQHn9oyg== +chromedriver@^87.0.0: + version "87.0.0" + resolved "https://registry.yarnpkg.com/chromedriver/-/chromedriver-87.0.0.tgz#e8390deed8ada791719a67ad6bf1116614f1ba2d" + integrity sha512-PY7FnHOQKfH0oPfSdhpLx5nEy5g4dGYySf2C/WZGkAaCaldYH8/3lPPucZ8MlOCi4bCSGoKoCUTeG6+wYWavvw== dependencies: "@testim/chrome-version" "^1.0.7" axios "^0.19.2"