diff --git a/docs/developer/plugin-list.asciidoc b/docs/developer/plugin-list.asciidoc index b3180a7a03874..88f29fa7e3cbe 100644 --- a/docs/developer/plugin-list.asciidoc +++ b/docs/developer/plugin-list.asciidoc @@ -95,7 +95,7 @@ in Kibana, e.g. visualizations. It has the form of a flyout panel. |{kib-repo}blob/{branch}/src/plugins/kibana_legacy/README.md[kibanaLegacy] -|This plugin will contain several helpers and services to integrate pieces of the legacy Kibana app with the new Kibana platform. +|This plugin contains several helpers and services to integrate pieces of the legacy Kibana app with the new Kibana platform. |{kib-repo}blob/{branch}/src/plugins/kibana_react/README.md[kibanaReact] @@ -172,6 +172,10 @@ which also contains the timelion APIs and backend, look at the vis_type_timelion |An API for: +|{kib-repo}blob/{branch}/src/plugins/url_forwarding/README.md[urlForwarding] +|This plugins contains helpers to redirect legacy URLs. It can be used to forward old URLs to their new counterparts. + + |{kib-repo}blob/{branch}/src/plugins/usage_collection/README.md[usageCollection] |Usage Collection allows collecting usage data for other services to consume (telemetry and monitoring). To integrate with the telemetry services for usage collection of your feature, there are 2 steps: diff --git a/docs/development/core/server/kibana-plugin-core-server.md b/docs/development/core/server/kibana-plugin-core-server.md index dfffdffb08a08..c16600d1d0492 100644 --- a/docs/development/core/server/kibana-plugin-core-server.md +++ b/docs/development/core/server/kibana-plugin-core-server.md @@ -28,6 +28,7 @@ The plugin integrates with the core system via lifecycle events: `setup` | [SavedObjectsErrorHelpers](./kibana-plugin-core-server.savedobjectserrorhelpers.md) | | | [SavedObjectsRepository](./kibana-plugin-core-server.savedobjectsrepository.md) | | | [SavedObjectsSerializer](./kibana-plugin-core-server.savedobjectsserializer.md) | A serializer that can be used to manually convert [raw](./kibana-plugin-core-server.savedobjectsrawdoc.md) or [sanitized](./kibana-plugin-core-server.savedobjectsanitizeddoc.md) documents to the other kind. | +| [SavedObjectsUtils](./kibana-plugin-core-server.savedobjectsutils.md) | | | [SavedObjectTypeRegistry](./kibana-plugin-core-server.savedobjecttyperegistry.md) | Registry holding information about all the registered [saved object types](./kibana-plugin-core-server.savedobjectstype.md). | ## Enumerations diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsbulkupdateobject.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsbulkupdateobject.md index e079e0fa51aac..d71eda6009284 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsbulkupdateobject.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsbulkupdateobject.md @@ -17,5 +17,6 @@ export interface SavedObjectsBulkUpdateObject extends PickPartial<T> | The data for a Saved Object is stored as an object in the attributes property. | | [id](./kibana-plugin-core-server.savedobjectsbulkupdateobject.id.md) | string | The ID of this Saved Object, guaranteed to be unique for all objects of the same type | +| [namespace](./kibana-plugin-core-server.savedobjectsbulkupdateobject.namespace.md) | string | Optional namespace string to use when searching for this object. If this is defined, it will supersede the namespace ID that is in [SavedObjectsBulkUpdateOptions](./kibana-plugin-core-server.savedobjectsbulkupdateoptions.md).Note: the default namespace's string representation is 'default', and its ID representation is undefined. | | [type](./kibana-plugin-core-server.savedobjectsbulkupdateobject.type.md) | string | The type of this Saved Object. Each plugin can define it's own custom Saved Object types. | diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsbulkupdateobject.namespace.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsbulkupdateobject.namespace.md new file mode 100644 index 0000000000000..544efcd3be909 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsbulkupdateobject.namespace.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsBulkUpdateObject](./kibana-plugin-core-server.savedobjectsbulkupdateobject.md) > [namespace](./kibana-plugin-core-server.savedobjectsbulkupdateobject.namespace.md) + +## SavedObjectsBulkUpdateObject.namespace property + +Optional namespace string to use when searching for this object. If this is defined, it will supersede the namespace ID that is in [SavedObjectsBulkUpdateOptions](./kibana-plugin-core-server.savedobjectsbulkupdateoptions.md). + +Note: the default namespace's string representation is `'default'`, and its ID representation is `undefined`. + +Signature: + +```typescript +namespace?: string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsutils.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsutils.md new file mode 100644 index 0000000000000..e365dfbcb5142 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsutils.md @@ -0,0 +1,20 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsUtils](./kibana-plugin-core-server.savedobjectsutils.md) + +## SavedObjectsUtils class + + +Signature: + +```typescript +export declare class SavedObjectsUtils +``` + +## Properties + +| Property | Modifiers | Type | Description | +| --- | --- | --- | --- | +| [namespaceIdToString](./kibana-plugin-core-server.savedobjectsutils.namespaceidtostring.md) | static | (namespace?: string | undefined) => string | Converts a given saved object namespace ID to its string representation. All namespace IDs have an identical string representation, with the exception of the undefined namespace ID (which has a namespace string of 'default'). | +| [namespaceStringToId](./kibana-plugin-core-server.savedobjectsutils.namespacestringtoid.md) | static | (namespace: string) => string | undefined | Converts a given saved object namespace string to its ID representation. All namespace strings have an identical ID representation, with the exception of the 'default' namespace string (which has a namespace ID of undefined). | + diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsutils.namespaceidtostring.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsutils.namespaceidtostring.md new file mode 100644 index 0000000000000..591505892e64f --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsutils.namespaceidtostring.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsUtils](./kibana-plugin-core-server.savedobjectsutils.md) > [namespaceIdToString](./kibana-plugin-core-server.savedobjectsutils.namespaceidtostring.md) + +## SavedObjectsUtils.namespaceIdToString property + +Converts a given saved object namespace ID to its string representation. All namespace IDs have an identical string representation, with the exception of the `undefined` namespace ID (which has a namespace string of `'default'`). + +Signature: + +```typescript +static namespaceIdToString: (namespace?: string | undefined) => string; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsutils.namespacestringtoid.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsutils.namespacestringtoid.md new file mode 100644 index 0000000000000..e052fe493b5ea --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsutils.namespacestringtoid.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsUtils](./kibana-plugin-core-server.savedobjectsutils.md) > [namespaceStringToId](./kibana-plugin-core-server.savedobjectsutils.namespacestringtoid.md) + +## SavedObjectsUtils.namespaceStringToId property + +Converts a given saved object namespace string to its ID representation. All namespace strings have an identical ID representation, with the exception of the `'default'` namespace string (which has a namespace ID of `undefined`). + +Signature: + +```typescript +static namespaceStringToId: (namespace: string) => string | undefined; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig._constructor_.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig._constructor_.md new file mode 100644 index 0000000000000..9287a08ff196b --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig._constructor_.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [(constructor)](./kibana-plugin-plugins-data-public.aggconfig._constructor_.md) + +## AggConfig.(constructor) + +Constructs a new instance of the `AggConfig` class + +Signature: + +```typescript +constructor(aggConfigs: IAggConfigs, opts: AggConfigOptions); +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| aggConfigs | IAggConfigs | | +| opts | AggConfigOptions | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.aggconfigs.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.aggconfigs.md new file mode 100644 index 0000000000000..f552bbd2d1cfc --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.aggconfigs.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [aggConfigs](./kibana-plugin-plugins-data-public.aggconfig.aggconfigs.md) + +## AggConfig.aggConfigs property + +Signature: + +```typescript +aggConfigs: IAggConfigs; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.brandnew.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.brandnew.md new file mode 100644 index 0000000000000..eb1f3af4c5b01 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.brandnew.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [brandNew](./kibana-plugin-plugins-data-public.aggconfig.brandnew.md) + +## AggConfig.brandNew property + +Signature: + +```typescript +brandNew?: boolean; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.createfilter.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.createfilter.md new file mode 100644 index 0000000000000..7ec0350f65321 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.createfilter.md @@ -0,0 +1,23 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [createFilter](./kibana-plugin-plugins-data-public.aggconfig.createfilter.md) + +## AggConfig.createFilter() method + +Signature: + +```typescript +createFilter(key: string, params?: {}): any; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| key | string | | +| params | {} | | + +Returns: + +`any` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.enabled.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.enabled.md new file mode 100644 index 0000000000000..82595ee5f5b63 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.enabled.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [enabled](./kibana-plugin-plugins-data-public.aggconfig.enabled.md) + +## AggConfig.enabled property + +Signature: + +```typescript +enabled: boolean; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.ensureids.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.ensureids.md new file mode 100644 index 0000000000000..04e0b82187a5f --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.ensureids.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [ensureIds](./kibana-plugin-plugins-data-public.aggconfig.ensureids.md) + +## AggConfig.ensureIds() method + +Ensure that all of the objects in the list have ids, the objects and list are modified by reference. + +Signature: + +```typescript +static ensureIds(list: any[]): any[]; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| list | any[] | | + +Returns: + +`any[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.fieldistimefield.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.fieldistimefield.md new file mode 100644 index 0000000000000..a1fde4dec25b1 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.fieldistimefield.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [fieldIsTimeField](./kibana-plugin-plugins-data-public.aggconfig.fieldistimefield.md) + +## AggConfig.fieldIsTimeField() method + +Signature: + +```typescript +fieldIsTimeField(): boolean | "" | undefined; +``` +Returns: + +`boolean | "" | undefined` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.fieldname.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.fieldname.md new file mode 100644 index 0000000000000..2d3acb7f026ff --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.fieldname.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [fieldName](./kibana-plugin-plugins-data-public.aggconfig.fieldname.md) + +## AggConfig.fieldName() method + +Signature: + +```typescript +fieldName(): any; +``` +Returns: + +`any` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getaggparams.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getaggparams.md new file mode 100644 index 0000000000000..f898844ff0273 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getaggparams.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [getAggParams](./kibana-plugin-plugins-data-public.aggconfig.getaggparams.md) + +## AggConfig.getAggParams() method + +Signature: + +```typescript +getAggParams(): import("./param_types/agg").AggParamType[]; +``` +Returns: + +`import("./param_types/agg").AggParamType[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getfield.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getfield.md new file mode 100644 index 0000000000000..1fb6f88c43171 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getfield.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [getField](./kibana-plugin-plugins-data-public.aggconfig.getfield.md) + +## AggConfig.getField() method + +Signature: + +```typescript +getField(): any; +``` +Returns: + +`any` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getfielddisplayname.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getfielddisplayname.md new file mode 100644 index 0000000000000..710499cee62dd --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getfielddisplayname.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [getFieldDisplayName](./kibana-plugin-plugins-data-public.aggconfig.getfielddisplayname.md) + +## AggConfig.getFieldDisplayName() method + +Signature: + +```typescript +getFieldDisplayName(): any; +``` +Returns: + +`any` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getindexpattern.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getindexpattern.md new file mode 100644 index 0000000000000..ed0e9d0fbb5de --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getindexpattern.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [getIndexPattern](./kibana-plugin-plugins-data-public.aggconfig.getindexpattern.md) + +## AggConfig.getIndexPattern() method + +Signature: + +```typescript +getIndexPattern(): import("../../../public").IndexPattern; +``` +Returns: + +`import("../../../public").IndexPattern` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getkey.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getkey.md new file mode 100644 index 0000000000000..a2a59fcf9ae31 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getkey.md @@ -0,0 +1,23 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [getKey](./kibana-plugin-plugins-data-public.aggconfig.getkey.md) + +## AggConfig.getKey() method + +Signature: + +```typescript +getKey(bucket: any, key?: string): any; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| bucket | any | | +| key | string | | + +Returns: + +`any` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getparam.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getparam.md new file mode 100644 index 0000000000000..ad4cd2fa175f8 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getparam.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [getParam](./kibana-plugin-plugins-data-public.aggconfig.getparam.md) + +## AggConfig.getParam() method + +Signature: + +```typescript +getParam(key: string): any; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| key | string | | + +Returns: + +`any` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getrequestaggs.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getrequestaggs.md new file mode 100644 index 0000000000000..773c2f5a7c0e9 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getrequestaggs.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [getRequestAggs](./kibana-plugin-plugins-data-public.aggconfig.getrequestaggs.md) + +## AggConfig.getRequestAggs() method + +Signature: + +```typescript +getRequestAggs(): AggConfig[]; +``` +Returns: + +`AggConfig[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getresponseaggs.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getresponseaggs.md new file mode 100644 index 0000000000000..cf515e68dcc57 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getresponseaggs.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [getResponseAggs](./kibana-plugin-plugins-data-public.aggconfig.getresponseaggs.md) + +## AggConfig.getResponseAggs() method + +Signature: + +```typescript +getResponseAggs(): AggConfig[]; +``` +Returns: + +`AggConfig[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.gettimerange.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.gettimerange.md new file mode 100644 index 0000000000000..897a6d8dda3f1 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.gettimerange.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [getTimeRange](./kibana-plugin-plugins-data-public.aggconfig.gettimerange.md) + +## AggConfig.getTimeRange() method + +Signature: + +```typescript +getTimeRange(): import("../../../public").TimeRange | undefined; +``` +Returns: + +`import("../../../public").TimeRange | undefined` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getvalue.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getvalue.md new file mode 100644 index 0000000000000..4fab1af3f6464 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.getvalue.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [getValue](./kibana-plugin-plugins-data-public.aggconfig.getvalue.md) + +## AggConfig.getValue() method + +Signature: + +```typescript +getValue(bucket: any): any; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| bucket | any | | + +Returns: + +`any` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.id.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.id.md new file mode 100644 index 0000000000000..1fa7a5c57e2a8 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.id.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [id](./kibana-plugin-plugins-data-public.aggconfig.id.md) + +## AggConfig.id property + +Signature: + +```typescript +id: string; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.isfilterable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.isfilterable.md new file mode 100644 index 0000000000000..a795ab1e91c2c --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.isfilterable.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [isFilterable](./kibana-plugin-plugins-data-public.aggconfig.isfilterable.md) + +## AggConfig.isFilterable() method + +Signature: + +```typescript +isFilterable(): boolean; +``` +Returns: + +`boolean` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.makelabel.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.makelabel.md new file mode 100644 index 0000000000000..65923ed0ae889 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.makelabel.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [makeLabel](./kibana-plugin-plugins-data-public.aggconfig.makelabel.md) + +## AggConfig.makeLabel() method + +Signature: + +```typescript +makeLabel(percentageMode?: boolean): any; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| percentageMode | boolean | | + +Returns: + +`any` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.md new file mode 100644 index 0000000000000..ceb90cffbf6ca --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.md @@ -0,0 +1,62 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) + +## AggConfig class + +Signature: + +```typescript +export declare class AggConfig +``` + +## Constructors + +| Constructor | Modifiers | Description | +| --- | --- | --- | +| [(constructor)(aggConfigs, opts)](./kibana-plugin-plugins-data-public.aggconfig._constructor_.md) | | Constructs a new instance of the AggConfig class | + +## Properties + +| Property | Modifiers | Type | Description | +| --- | --- | --- | --- | +| [aggConfigs](./kibana-plugin-plugins-data-public.aggconfig.aggconfigs.md) | | IAggConfigs | | +| [brandNew](./kibana-plugin-plugins-data-public.aggconfig.brandnew.md) | | boolean | | +| [enabled](./kibana-plugin-plugins-data-public.aggconfig.enabled.md) | | boolean | | +| [id](./kibana-plugin-plugins-data-public.aggconfig.id.md) | | string | | +| [params](./kibana-plugin-plugins-data-public.aggconfig.params.md) | | any | | +| [parent](./kibana-plugin-plugins-data-public.aggconfig.parent.md) | | IAggConfigs | | +| [schema](./kibana-plugin-plugins-data-public.aggconfig.schema.md) | | string | | +| [type](./kibana-plugin-plugins-data-public.aggconfig.type.md) | | IAggType | | + +## Methods + +| Method | Modifiers | Description | +| --- | --- | --- | +| [createFilter(key, params)](./kibana-plugin-plugins-data-public.aggconfig.createfilter.md) | | | +| [ensureIds(list)](./kibana-plugin-plugins-data-public.aggconfig.ensureids.md) | static | Ensure that all of the objects in the list have ids, the objects and list are modified by reference. | +| [fieldIsTimeField()](./kibana-plugin-plugins-data-public.aggconfig.fieldistimefield.md) | | | +| [fieldName()](./kibana-plugin-plugins-data-public.aggconfig.fieldname.md) | | | +| [getAggParams()](./kibana-plugin-plugins-data-public.aggconfig.getaggparams.md) | | | +| [getField()](./kibana-plugin-plugins-data-public.aggconfig.getfield.md) | | | +| [getFieldDisplayName()](./kibana-plugin-plugins-data-public.aggconfig.getfielddisplayname.md) | | | +| [getIndexPattern()](./kibana-plugin-plugins-data-public.aggconfig.getindexpattern.md) | | | +| [getKey(bucket, key)](./kibana-plugin-plugins-data-public.aggconfig.getkey.md) | | | +| [getParam(key)](./kibana-plugin-plugins-data-public.aggconfig.getparam.md) | | | +| [getRequestAggs()](./kibana-plugin-plugins-data-public.aggconfig.getrequestaggs.md) | | | +| [getResponseAggs()](./kibana-plugin-plugins-data-public.aggconfig.getresponseaggs.md) | | | +| [getTimeRange()](./kibana-plugin-plugins-data-public.aggconfig.gettimerange.md) | | | +| [getValue(bucket)](./kibana-plugin-plugins-data-public.aggconfig.getvalue.md) | | | +| [isFilterable()](./kibana-plugin-plugins-data-public.aggconfig.isfilterable.md) | | | +| [makeLabel(percentageMode)](./kibana-plugin-plugins-data-public.aggconfig.makelabel.md) | | | +| [nextId(list)](./kibana-plugin-plugins-data-public.aggconfig.nextid.md) | static | Calculate the next id based on the ids in this list {array} list - a list of objects with id properties | +| [onSearchRequestStart(searchSource, options)](./kibana-plugin-plugins-data-public.aggconfig.onsearchrequeststart.md) | | Hook for pre-flight logic, see AggType\#onSearchRequestStart | +| [serialize()](./kibana-plugin-plugins-data-public.aggconfig.serialize.md) | | | +| [setParams(from)](./kibana-plugin-plugins-data-public.aggconfig.setparams.md) | | Write the current values to this.params, filling in the defaults as we go | +| [setType(type)](./kibana-plugin-plugins-data-public.aggconfig.settype.md) | | | +| [toDsl(aggConfigs)](./kibana-plugin-plugins-data-public.aggconfig.todsl.md) | | Convert this aggConfig to its dsl syntax.Adds params and adhoc subaggs to a pojo, then returns it | +| [toExpressionAst()](./kibana-plugin-plugins-data-public.aggconfig.toexpressionast.md) | | | +| [toJSON()](./kibana-plugin-plugins-data-public.aggconfig.tojson.md) | | | +| [toSerializedFieldFormat()](./kibana-plugin-plugins-data-public.aggconfig.toserializedfieldformat.md) | | Returns a serialized field format for the field used in this agg. This can be passed to fieldFormats.deserialize to get the field format instance. | +| [write(aggs)](./kibana-plugin-plugins-data-public.aggconfig.write.md) | | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.nextid.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.nextid.md new file mode 100644 index 0000000000000..ab524a6d1c4f1 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.nextid.md @@ -0,0 +1,26 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [nextId](./kibana-plugin-plugins-data-public.aggconfig.nextid.md) + +## AggConfig.nextId() method + +Calculate the next id based on the ids in this list + + {array} list - a list of objects with id properties + +Signature: + +```typescript +static nextId(list: IAggConfig[]): number; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| list | IAggConfig[] | | + +Returns: + +`number` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.onsearchrequeststart.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.onsearchrequeststart.md new file mode 100644 index 0000000000000..81df7866560e3 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.onsearchrequeststart.md @@ -0,0 +1,25 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [onSearchRequestStart](./kibana-plugin-plugins-data-public.aggconfig.onsearchrequeststart.md) + +## AggConfig.onSearchRequestStart() method + +Hook for pre-flight logic, see AggType\#onSearchRequestStart + +Signature: + +```typescript +onSearchRequestStart(searchSource: ISearchSource, options?: ISearchOptions): Promise | Promise; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| searchSource | ISearchSource | | +| options | ISearchOptions | | + +Returns: + +`Promise | Promise` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.params.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.params.md new file mode 100644 index 0000000000000..5bdb67f53b519 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.params.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [params](./kibana-plugin-plugins-data-public.aggconfig.params.md) + +## AggConfig.params property + +Signature: + +```typescript +params: any; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.parent.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.parent.md new file mode 100644 index 0000000000000..53d028457a9ae --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.parent.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [parent](./kibana-plugin-plugins-data-public.aggconfig.parent.md) + +## AggConfig.parent property + +Signature: + +```typescript +parent?: IAggConfigs; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.schema.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.schema.md new file mode 100644 index 0000000000000..afbf685951356 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.schema.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [schema](./kibana-plugin-plugins-data-public.aggconfig.schema.md) + +## AggConfig.schema property + +Signature: + +```typescript +schema?: string; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.serialize.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.serialize.md new file mode 100644 index 0000000000000..b0eebdbcc11ec --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.serialize.md @@ -0,0 +1,17 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [serialize](./kibana-plugin-plugins-data-public.aggconfig.serialize.md) + +## AggConfig.serialize() method + +Signature: + +```typescript +serialize(): AggConfigSerialized; +``` +Returns: + +`AggConfigSerialized` + +Returns a serialized representation of an AggConfig. + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.setparams.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.setparams.md new file mode 100644 index 0000000000000..cb495b7653f8a --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.setparams.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [setParams](./kibana-plugin-plugins-data-public.aggconfig.setparams.md) + +## AggConfig.setParams() method + +Write the current values to this.params, filling in the defaults as we go + +Signature: + +```typescript +setParams(from: any): void; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| from | any | | + +Returns: + +`void` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.settype.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.settype.md new file mode 100644 index 0000000000000..0b07186a6ca33 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.settype.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [setType](./kibana-plugin-plugins-data-public.aggconfig.settype.md) + +## AggConfig.setType() method + +Signature: + +```typescript +setType(type: IAggType): void; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| type | IAggType | | + +Returns: + +`void` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.todsl.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.todsl.md new file mode 100644 index 0000000000000..ac655c2a88a7b --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.todsl.md @@ -0,0 +1,26 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [toDsl](./kibana-plugin-plugins-data-public.aggconfig.todsl.md) + +## AggConfig.toDsl() method + +Convert this aggConfig to its dsl syntax. + +Adds params and adhoc subaggs to a pojo, then returns it + +Signature: + +```typescript +toDsl(aggConfigs?: IAggConfigs): any; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| aggConfigs | IAggConfigs | | + +Returns: + +`any` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.toexpressionast.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.toexpressionast.md new file mode 100644 index 0000000000000..99001e81fde49 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.toexpressionast.md @@ -0,0 +1,17 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [toExpressionAst](./kibana-plugin-plugins-data-public.aggconfig.toexpressionast.md) + +## AggConfig.toExpressionAst() method + +Signature: + +```typescript +toExpressionAst(): ExpressionAstFunction | undefined; +``` +Returns: + +`ExpressionAstFunction | undefined` + +Returns an ExpressionAst representing the function for this agg type. + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.tojson.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.tojson.md new file mode 100644 index 0000000000000..aa639aa574076 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.tojson.md @@ -0,0 +1,20 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [toJSON](./kibana-plugin-plugins-data-public.aggconfig.tojson.md) + +## AggConfig.toJSON() method + +> Warning: This API is now obsolete. +> +> - Use serialize() instead. +> + +Signature: + +```typescript +toJSON(): AggConfigSerialized; +``` +Returns: + +`AggConfigSerialized` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.toserializedfieldformat.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.toserializedfieldformat.md new file mode 100644 index 0000000000000..7a75950f9cc6d --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.toserializedfieldformat.md @@ -0,0 +1,17 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [toSerializedFieldFormat](./kibana-plugin-plugins-data-public.aggconfig.toserializedfieldformat.md) + +## AggConfig.toSerializedFieldFormat() method + +Returns a serialized field format for the field used in this agg. This can be passed to fieldFormats.deserialize to get the field format instance. + +Signature: + +```typescript +toSerializedFieldFormat(): {} | Ensure, SerializableState>; +``` +Returns: + +`{} | Ensure, SerializableState>` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.type.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.type.md new file mode 100644 index 0000000000000..9dc44caee42e8 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.type.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [type](./kibana-plugin-plugins-data-public.aggconfig.type.md) + +## AggConfig.type property + +Signature: + +```typescript +get type(): IAggType; + +set type(type: IAggType); +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.write.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.write.md new file mode 100644 index 0000000000000..f98394b57cac3 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfig.write.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) > [write](./kibana-plugin-plugins-data-public.aggconfig.write.md) + +## AggConfig.write() method + +Signature: + +```typescript +write(aggs?: IAggConfigs): Record; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| aggs | IAggConfigs | | + +Returns: + +`Record` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs._constructor_.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs._constructor_.md new file mode 100644 index 0000000000000..c9e08b9712480 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs._constructor_.md @@ -0,0 +1,32 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [(constructor)](./kibana-plugin-plugins-data-public.aggconfigs._constructor_.md) + +## AggConfigs.(constructor) + +Constructs a new instance of the `AggConfigs` class + +Signature: + +```typescript +constructor(indexPattern: IndexPattern, configStates: Pick & Pick<{ + type: string | IAggType; + }, "type"> & Pick<{ + type: string | IAggType; + }, never>, "enabled" | "type" | "schema" | "id" | "params">[] | undefined, opts: AggConfigsOptions); +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| indexPattern | IndexPattern | | +| configStates | Pick<Pick<{
type: string;
enabled?: boolean | undefined;
id?: string | undefined;
params?: {} | import("./agg_config").SerializableState | undefined;
schema?: string | undefined;
}, "enabled" | "schema" | "id" | "params"> & Pick<{
type: string | IAggType;
}, "type"> & Pick<{
type: string | IAggType;
}, never>, "enabled" | "type" | "schema" | "id" | "params">[] | undefined | | +| opts | AggConfigsOptions | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.aggs.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.aggs.md new file mode 100644 index 0000000000000..0d217e037ecb1 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.aggs.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [aggs](./kibana-plugin-plugins-data-public.aggconfigs.aggs.md) + +## AggConfigs.aggs property + +Signature: + +```typescript +aggs: IAggConfig[]; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byid.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byid.md new file mode 100644 index 0000000000000..14d65ada5e39d --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byid.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [byId](./kibana-plugin-plugins-data-public.aggconfigs.byid.md) + +## AggConfigs.byId() method + +Signature: + +```typescript +byId(id: string): AggConfig | undefined; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| id | string | | + +Returns: + +`AggConfig | undefined` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byindex.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byindex.md new file mode 100644 index 0000000000000..5977c81ddaf36 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byindex.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [byIndex](./kibana-plugin-plugins-data-public.aggconfigs.byindex.md) + +## AggConfigs.byIndex() method + +Signature: + +```typescript +byIndex(index: number): AggConfig; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| index | number | | + +Returns: + +`AggConfig` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byname.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byname.md new file mode 100644 index 0000000000000..772ba1f074d0d --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byname.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [byName](./kibana-plugin-plugins-data-public.aggconfigs.byname.md) + +## AggConfigs.byName() method + +Signature: + +```typescript +byName(name: string): AggConfig[]; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| name | string | | + +Returns: + +`AggConfig[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byschemaname.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byschemaname.md new file mode 100644 index 0000000000000..3a7c6a5f89e17 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.byschemaname.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [bySchemaName](./kibana-plugin-plugins-data-public.aggconfigs.byschemaname.md) + +## AggConfigs.bySchemaName() method + +Signature: + +```typescript +bySchemaName(schema: string): AggConfig[]; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| schema | string | | + +Returns: + +`AggConfig[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.bytype.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.bytype.md new file mode 100644 index 0000000000000..8bbf85ce4f29b --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.bytype.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [byType](./kibana-plugin-plugins-data-public.aggconfigs.bytype.md) + +## AggConfigs.byType() method + +Signature: + +```typescript +byType(type: string): AggConfig[]; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| type | string | | + +Returns: + +`AggConfig[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.bytypename.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.bytypename.md new file mode 100644 index 0000000000000..97f05837493f2 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.bytypename.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [byTypeName](./kibana-plugin-plugins-data-public.aggconfigs.bytypename.md) + +## AggConfigs.byTypeName() method + +Signature: + +```typescript +byTypeName(type: string): AggConfig[]; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| type | string | | + +Returns: + +`AggConfig[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.clone.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.clone.md new file mode 100644 index 0000000000000..0206f3c6b4751 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.clone.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [clone](./kibana-plugin-plugins-data-public.aggconfigs.clone.md) + +## AggConfigs.clone() method + +Signature: + +```typescript +clone({ enabledOnly }?: { + enabledOnly?: boolean | undefined; + }): AggConfigs; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| { enabledOnly } | {
enabledOnly?: boolean | undefined;
} | | + +Returns: + +`AggConfigs` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.createaggconfig.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.createaggconfig.md new file mode 100644 index 0000000000000..2ccded7c74e4c --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.createaggconfig.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [createAggConfig](./kibana-plugin-plugins-data-public.aggconfigs.createaggconfig.md) + +## AggConfigs.createAggConfig property + +Signature: + +```typescript +createAggConfig: (params: CreateAggConfigParams, { addToAggConfigs }?: { + addToAggConfigs?: boolean | undefined; + }) => T; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getall.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getall.md new file mode 100644 index 0000000000000..091ec1ce416c3 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getall.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [getAll](./kibana-plugin-plugins-data-public.aggconfigs.getall.md) + +## AggConfigs.getAll() method + +Signature: + +```typescript +getAll(): AggConfig[]; +``` +Returns: + +`AggConfig[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getrequestaggbyid.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getrequestaggbyid.md new file mode 100644 index 0000000000000..f375648ca1cb7 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getrequestaggbyid.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [getRequestAggById](./kibana-plugin-plugins-data-public.aggconfigs.getrequestaggbyid.md) + +## AggConfigs.getRequestAggById() method + +Signature: + +```typescript +getRequestAggById(id: string): AggConfig | undefined; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| id | string | | + +Returns: + +`AggConfig | undefined` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getrequestaggs.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getrequestaggs.md new file mode 100644 index 0000000000000..f4db6e373f5c3 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getrequestaggs.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [getRequestAggs](./kibana-plugin-plugins-data-public.aggconfigs.getrequestaggs.md) + +## AggConfigs.getRequestAggs() method + +Signature: + +```typescript +getRequestAggs(): AggConfig[]; +``` +Returns: + +`AggConfig[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getresponseaggbyid.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getresponseaggbyid.md new file mode 100644 index 0000000000000..ab31c74f6000d --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getresponseaggbyid.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [getResponseAggById](./kibana-plugin-plugins-data-public.aggconfigs.getresponseaggbyid.md) + +## AggConfigs.getResponseAggById() method + +Find a response agg by it's id. This may be an agg in the aggConfigs, or one created specifically for a response value + +Signature: + +```typescript +getResponseAggById(id: string): AggConfig | undefined; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| id | string | | + +Returns: + +`AggConfig | undefined` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getresponseaggs.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getresponseaggs.md new file mode 100644 index 0000000000000..47e26bdea9e9c --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.getresponseaggs.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [getResponseAggs](./kibana-plugin-plugins-data-public.aggconfigs.getresponseaggs.md) + +## AggConfigs.getResponseAggs() method + +Gets the AggConfigs (and possibly ResponseAggConfigs) that represent the values that will be produced when all aggs are run. + +With multi-value metric aggs it is possible for a single agg request to result in multiple agg values, which is why the length of a vis' responseValuesAggs may be different than the vis' aggs + + {array\[AggConfig\]} + +Signature: + +```typescript +getResponseAggs(): AggConfig[]; +``` +Returns: + +`AggConfig[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.indexpattern.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.indexpattern.md new file mode 100644 index 0000000000000..9bd91e185df1e --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.indexpattern.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [indexPattern](./kibana-plugin-plugins-data-public.aggconfigs.indexpattern.md) + +## AggConfigs.indexPattern property + +Signature: + +```typescript +indexPattern: IndexPattern; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.jsondataequals.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.jsondataequals.md new file mode 100644 index 0000000000000..d94c3959cd6a2 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.jsondataequals.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [jsonDataEquals](./kibana-plugin-plugins-data-public.aggconfigs.jsondataequals.md) + +## AggConfigs.jsonDataEquals() method + +Data-by-data comparison of this Aggregation Ignores the non-array indexes + +Signature: + +```typescript +jsonDataEquals(aggConfigs: AggConfig[]): boolean; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| aggConfigs | AggConfig[] | | + +Returns: + +`boolean` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.md new file mode 100644 index 0000000000000..c0ba1bbeea334 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.md @@ -0,0 +1,48 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) + +## AggConfigs class + +Signature: + +```typescript +export declare class AggConfigs +``` + +## Constructors + +| Constructor | Modifiers | Description | +| --- | --- | --- | +| [(constructor)(indexPattern, configStates, opts)](./kibana-plugin-plugins-data-public.aggconfigs._constructor_.md) | | Constructs a new instance of the AggConfigs class | + +## Properties + +| Property | Modifiers | Type | Description | +| --- | --- | --- | --- | +| [aggs](./kibana-plugin-plugins-data-public.aggconfigs.aggs.md) | | IAggConfig[] | | +| [createAggConfig](./kibana-plugin-plugins-data-public.aggconfigs.createaggconfig.md) | | <T extends AggConfig = AggConfig>(params: CreateAggConfigParams, { addToAggConfigs }?: {
addToAggConfigs?: boolean | undefined;
}) => T | | +| [indexPattern](./kibana-plugin-plugins-data-public.aggconfigs.indexpattern.md) | | IndexPattern | | +| [timeRange](./kibana-plugin-plugins-data-public.aggconfigs.timerange.md) | | TimeRange | | + +## Methods + +| Method | Modifiers | Description | +| --- | --- | --- | +| [byId(id)](./kibana-plugin-plugins-data-public.aggconfigs.byid.md) | | | +| [byIndex(index)](./kibana-plugin-plugins-data-public.aggconfigs.byindex.md) | | | +| [byName(name)](./kibana-plugin-plugins-data-public.aggconfigs.byname.md) | | | +| [bySchemaName(schema)](./kibana-plugin-plugins-data-public.aggconfigs.byschemaname.md) | | | +| [byType(type)](./kibana-plugin-plugins-data-public.aggconfigs.bytype.md) | | | +| [byTypeName(type)](./kibana-plugin-plugins-data-public.aggconfigs.bytypename.md) | | | +| [clone({ enabledOnly })](./kibana-plugin-plugins-data-public.aggconfigs.clone.md) | | | +| [getAll()](./kibana-plugin-plugins-data-public.aggconfigs.getall.md) | | | +| [getRequestAggById(id)](./kibana-plugin-plugins-data-public.aggconfigs.getrequestaggbyid.md) | | | +| [getRequestAggs()](./kibana-plugin-plugins-data-public.aggconfigs.getrequestaggs.md) | | | +| [getResponseAggById(id)](./kibana-plugin-plugins-data-public.aggconfigs.getresponseaggbyid.md) | | Find a response agg by it's id. This may be an agg in the aggConfigs, or one created specifically for a response value | +| [getResponseAggs()](./kibana-plugin-plugins-data-public.aggconfigs.getresponseaggs.md) | | Gets the AggConfigs (and possibly ResponseAggConfigs) that represent the values that will be produced when all aggs are run.With multi-value metric aggs it is possible for a single agg request to result in multiple agg values, which is why the length of a vis' responseValuesAggs may be different than the vis' aggs {array\[AggConfig\]} | +| [jsonDataEquals(aggConfigs)](./kibana-plugin-plugins-data-public.aggconfigs.jsondataequals.md) | | Data-by-data comparison of this Aggregation Ignores the non-array indexes | +| [onSearchRequestStart(searchSource, options)](./kibana-plugin-plugins-data-public.aggconfigs.onsearchrequeststart.md) | | | +| [setTimeRange(timeRange)](./kibana-plugin-plugins-data-public.aggconfigs.settimerange.md) | | | +| [toDsl(hierarchical)](./kibana-plugin-plugins-data-public.aggconfigs.todsl.md) | | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.onsearchrequeststart.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.onsearchrequeststart.md new file mode 100644 index 0000000000000..3ae7af408563c --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.onsearchrequeststart.md @@ -0,0 +1,23 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [onSearchRequestStart](./kibana-plugin-plugins-data-public.aggconfigs.onsearchrequeststart.md) + +## AggConfigs.onSearchRequestStart() method + +Signature: + +```typescript +onSearchRequestStart(searchSource: ISearchSource, options?: ISearchOptions): Promise<[unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown]>; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| searchSource | ISearchSource | | +| options | ISearchOptions | | + +Returns: + +`Promise<[unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown]>` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.settimerange.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.settimerange.md new file mode 100644 index 0000000000000..77530f02bc9a3 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.settimerange.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [setTimeRange](./kibana-plugin-plugins-data-public.aggconfigs.settimerange.md) + +## AggConfigs.setTimeRange() method + +Signature: + +```typescript +setTimeRange(timeRange: TimeRange): void; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| timeRange | TimeRange | | + +Returns: + +`void` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.timerange.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.timerange.md new file mode 100644 index 0000000000000..b4caef6c7f6d2 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.timerange.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [timeRange](./kibana-plugin-plugins-data-public.aggconfigs.timerange.md) + +## AggConfigs.timeRange property + +Signature: + +```typescript +timeRange?: TimeRange; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.todsl.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.todsl.md new file mode 100644 index 0000000000000..055c4113ca3e4 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggconfigs.todsl.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) > [toDsl](./kibana-plugin-plugins-data-public.aggconfigs.todsl.md) + +## AggConfigs.toDsl() method + +Signature: + +```typescript +toDsl(hierarchical?: boolean): Record; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| hierarchical | boolean | | + +Returns: + +`Record` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggsstart.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggsstart.md new file mode 100644 index 0000000000000..7bdf9d6501203 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.aggsstart.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AggsStart](./kibana-plugin-plugins-data-public.aggsstart.md) + +## AggsStart type + +AggsStart represents the actual external contract as AggsCommonStart is only used internally. The difference is that AggsStart includes the typings for the registry with initialized agg types. + +Signature: + +```typescript +export declare type AggsStart = Assign; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.autocompletestart.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.autocompletestart.md new file mode 100644 index 0000000000000..44cee8c32421d --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.autocompletestart.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [AutocompleteStart](./kibana-plugin-plugins-data-public.autocompletestart.md) + +## AutocompleteStart type + +\* + +Signature: + +```typescript +export declare type AutocompleteStart = ReturnType; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginsetup.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginsetup.md index dba1d79e78682..fc5624aeddce1 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginsetup.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginsetup.md @@ -4,6 +4,8 @@ ## DataPublicPluginSetup interface +Data plugin public Setup contract + Signature: ```typescript diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.actions.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.actions.md index 25ce6eaa688f8..10997c94fab06 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.actions.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.actions.md @@ -4,11 +4,10 @@ ## DataPublicPluginStart.actions property +filter creation utilities [DataPublicPluginStartActions](./kibana-plugin-plugins-data-public.datapublicpluginstartactions.md) + Signature: ```typescript -actions: { - createFiltersFromValueClickAction: typeof createFiltersFromValueClickAction; - createFiltersFromRangeSelectAction: typeof createFiltersFromRangeSelectAction; - }; +actions: DataPublicPluginStartActions; ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.autocomplete.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.autocomplete.md index d2e5aee7d90dd..8a09a10cccb24 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.autocomplete.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.autocomplete.md @@ -4,6 +4,8 @@ ## DataPublicPluginStart.autocomplete property +autocomplete service [AutocompleteStart](./kibana-plugin-plugins-data-public.autocompletestart.md) + Signature: ```typescript diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.fieldformats.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.fieldformats.md index dd4b38f64d10b..344044b38f7de 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.fieldformats.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.fieldformats.md @@ -4,6 +4,8 @@ ## DataPublicPluginStart.fieldFormats property +field formats service [FieldFormatsStart](./kibana-plugin-plugins-data-public.fieldformatsstart.md) + Signature: ```typescript diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.indexpatterns.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.indexpatterns.md index b3dd6a61760a6..0cf1e3101713d 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.indexpatterns.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.indexpatterns.md @@ -4,6 +4,8 @@ ## DataPublicPluginStart.indexPatterns property +index patterns service [IndexPatternsContract](./kibana-plugin-plugins-data-public.indexpatternscontract.md) + Signature: ```typescript diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.md index 4f43f10ce089e..7bae0bca701bf 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.md @@ -4,6 +4,8 @@ ## DataPublicPluginStart interface +Data plugin public Start contract + Signature: ```typescript @@ -14,11 +16,11 @@ export interface DataPublicPluginStart | Property | Type | Description | | --- | --- | --- | -| [actions](./kibana-plugin-plugins-data-public.datapublicpluginstart.actions.md) | {
createFiltersFromValueClickAction: typeof createFiltersFromValueClickAction;
createFiltersFromRangeSelectAction: typeof createFiltersFromRangeSelectAction;
} | | -| [autocomplete](./kibana-plugin-plugins-data-public.datapublicpluginstart.autocomplete.md) | AutocompleteStart | | -| [fieldFormats](./kibana-plugin-plugins-data-public.datapublicpluginstart.fieldformats.md) | FieldFormatsStart | | -| [indexPatterns](./kibana-plugin-plugins-data-public.datapublicpluginstart.indexpatterns.md) | IndexPatternsContract | | -| [query](./kibana-plugin-plugins-data-public.datapublicpluginstart.query.md) | QueryStart | | -| [search](./kibana-plugin-plugins-data-public.datapublicpluginstart.search.md) | ISearchStart | | -| [ui](./kibana-plugin-plugins-data-public.datapublicpluginstart.ui.md) | {
IndexPatternSelect: React.ComponentType<IndexPatternSelectProps>;
SearchBar: React.ComponentType<StatefulSearchBarProps>;
} | | +| [actions](./kibana-plugin-plugins-data-public.datapublicpluginstart.actions.md) | DataPublicPluginStartActions | filter creation utilities [DataPublicPluginStartActions](./kibana-plugin-plugins-data-public.datapublicpluginstartactions.md) | +| [autocomplete](./kibana-plugin-plugins-data-public.datapublicpluginstart.autocomplete.md) | AutocompleteStart | autocomplete service [AutocompleteStart](./kibana-plugin-plugins-data-public.autocompletestart.md) | +| [fieldFormats](./kibana-plugin-plugins-data-public.datapublicpluginstart.fieldformats.md) | FieldFormatsStart | field formats service [FieldFormatsStart](./kibana-plugin-plugins-data-public.fieldformatsstart.md) | +| [indexPatterns](./kibana-plugin-plugins-data-public.datapublicpluginstart.indexpatterns.md) | IndexPatternsContract | index patterns service [IndexPatternsContract](./kibana-plugin-plugins-data-public.indexpatternscontract.md) | +| [query](./kibana-plugin-plugins-data-public.datapublicpluginstart.query.md) | QueryStart | query service [QueryStart](./kibana-plugin-plugins-data-public.querystart.md) | +| [search](./kibana-plugin-plugins-data-public.datapublicpluginstart.search.md) | ISearchStart | search service [ISearchStart](./kibana-plugin-plugins-data-public.isearchstart.md) | +| [ui](./kibana-plugin-plugins-data-public.datapublicpluginstart.ui.md) | DataPublicPluginStartUi | prewired UI components [DataPublicPluginStartUi](./kibana-plugin-plugins-data-public.datapublicpluginstartui.md) | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.query.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.query.md index a44e250077ed4..16ba5dafbb264 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.query.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.query.md @@ -4,6 +4,8 @@ ## DataPublicPluginStart.query property +query service [QueryStart](./kibana-plugin-plugins-data-public.querystart.md) + Signature: ```typescript diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.search.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.search.md index eec00e7b13e9d..98832d7ca11d8 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.search.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.search.md @@ -4,6 +4,8 @@ ## DataPublicPluginStart.search property +search service [ISearchStart](./kibana-plugin-plugins-data-public.isearchstart.md) + Signature: ```typescript diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.ui.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.ui.md index 9c24216834371..671a1814ac644 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.ui.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstart.ui.md @@ -4,11 +4,10 @@ ## DataPublicPluginStart.ui property +prewired UI components [DataPublicPluginStartUi](./kibana-plugin-plugins-data-public.datapublicpluginstartui.md) + Signature: ```typescript -ui: { - IndexPatternSelect: React.ComponentType; - SearchBar: React.ComponentType; - }; +ui: DataPublicPluginStartUi; ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartactions.createfiltersfromrangeselectaction.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartactions.createfiltersfromrangeselectaction.md new file mode 100644 index 0000000000000..c954e0095cbb6 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartactions.createfiltersfromrangeselectaction.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [DataPublicPluginStartActions](./kibana-plugin-plugins-data-public.datapublicpluginstartactions.md) > [createFiltersFromRangeSelectAction](./kibana-plugin-plugins-data-public.datapublicpluginstartactions.createfiltersfromrangeselectaction.md) + +## DataPublicPluginStartActions.createFiltersFromRangeSelectAction property + +Signature: + +```typescript +createFiltersFromRangeSelectAction: typeof createFiltersFromRangeSelectAction; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartactions.createfiltersfromvalueclickaction.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartactions.createfiltersfromvalueclickaction.md new file mode 100644 index 0000000000000..70bd5091f3604 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartactions.createfiltersfromvalueclickaction.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [DataPublicPluginStartActions](./kibana-plugin-plugins-data-public.datapublicpluginstartactions.md) > [createFiltersFromValueClickAction](./kibana-plugin-plugins-data-public.datapublicpluginstartactions.createfiltersfromvalueclickaction.md) + +## DataPublicPluginStartActions.createFiltersFromValueClickAction property + +Signature: + +```typescript +createFiltersFromValueClickAction: typeof createFiltersFromValueClickAction; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartactions.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartactions.md new file mode 100644 index 0000000000000..d44c9e892cb80 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartactions.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [DataPublicPluginStartActions](./kibana-plugin-plugins-data-public.datapublicpluginstartactions.md) + +## DataPublicPluginStartActions interface + +utilities to generate filters from action context + +Signature: + +```typescript +export interface DataPublicPluginStartActions +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [createFiltersFromRangeSelectAction](./kibana-plugin-plugins-data-public.datapublicpluginstartactions.createfiltersfromrangeselectaction.md) | typeof createFiltersFromRangeSelectAction | | +| [createFiltersFromValueClickAction](./kibana-plugin-plugins-data-public.datapublicpluginstartactions.createfiltersfromvalueclickaction.md) | typeof createFiltersFromValueClickAction | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartui.indexpatternselect.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartui.indexpatternselect.md new file mode 100644 index 0000000000000..eac29dc5de70d --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartui.indexpatternselect.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [DataPublicPluginStartUi](./kibana-plugin-plugins-data-public.datapublicpluginstartui.md) > [IndexPatternSelect](./kibana-plugin-plugins-data-public.datapublicpluginstartui.indexpatternselect.md) + +## DataPublicPluginStartUi.IndexPatternSelect property + +Signature: + +```typescript +IndexPatternSelect: React.ComponentType; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartui.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartui.md new file mode 100644 index 0000000000000..3d827c0db465b --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartui.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [DataPublicPluginStartUi](./kibana-plugin-plugins-data-public.datapublicpluginstartui.md) + +## DataPublicPluginStartUi interface + +Data plugin prewired UI components + +Signature: + +```typescript +export interface DataPublicPluginStartUi +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [IndexPatternSelect](./kibana-plugin-plugins-data-public.datapublicpluginstartui.indexpatternselect.md) | React.ComponentType<IndexPatternSelectProps> | | +| [SearchBar](./kibana-plugin-plugins-data-public.datapublicpluginstartui.searchbar.md) | React.ComponentType<StatefulSearchBarProps> | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartui.searchbar.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartui.searchbar.md new file mode 100644 index 0000000000000..06339d14cde24 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.datapublicpluginstartui.searchbar.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [DataPublicPluginStartUi](./kibana-plugin-plugins-data-public.datapublicpluginstartui.md) > [SearchBar](./kibana-plugin-plugins-data-public.datapublicpluginstartui.searchbar.md) + +## DataPublicPluginStartUi.SearchBar property + +Signature: + +```typescript +SearchBar: React.ComponentType; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.fieldformatsstart.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.fieldformatsstart.md new file mode 100644 index 0000000000000..1a0a08f44451a --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.fieldformatsstart.md @@ -0,0 +1,14 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [FieldFormatsStart](./kibana-plugin-plugins-data-public.fieldformatsstart.md) + +## FieldFormatsStart type + + +Signature: + +```typescript +export declare type FieldFormatsStart = Omit & { + deserialize: FormatFactory; +}; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsetup.aggs.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsetup.aggs.md new file mode 100644 index 0000000000000..ad97820d4d760 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsetup.aggs.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchSetup](./kibana-plugin-plugins-data-public.isearchsetup.md) > [aggs](./kibana-plugin-plugins-data-public.isearchsetup.aggs.md) + +## ISearchSetup.aggs property + +Signature: + +```typescript +aggs: AggsSetup; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsetup.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsetup.md new file mode 100644 index 0000000000000..b68c4d61e4e03 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsetup.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchSetup](./kibana-plugin-plugins-data-public.isearchsetup.md) + +## ISearchSetup interface + +The setup contract exposed by the Search plugin exposes the search strategy extension point. + +Signature: + +```typescript +export interface ISearchSetup +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [aggs](./kibana-plugin-plugins-data-public.isearchsetup.aggs.md) | AggsSetup | | +| [usageCollector](./kibana-plugin-plugins-data-public.isearchsetup.usagecollector.md) | SearchUsageCollector | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsetup.usagecollector.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsetup.usagecollector.md new file mode 100644 index 0000000000000..908a842974f25 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsetup.usagecollector.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchSetup](./kibana-plugin-plugins-data-public.isearchsetup.md) > [usageCollector](./kibana-plugin-plugins-data-public.isearchsetup.usagecollector.md) + +## ISearchSetup.usageCollector property + +Signature: + +```typescript +usageCollector?: SearchUsageCollector; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsource.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsource.md index 4b9f6e3594dc5..43e10d0bef57a 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsource.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchsource.md @@ -4,7 +4,7 @@ ## ISearchSource type -\* +search source interface Signature: diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.aggs.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.aggs.md new file mode 100644 index 0000000000000..993c6bf5a922b --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.aggs.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchStart](./kibana-plugin-plugins-data-public.isearchstart.md) > [aggs](./kibana-plugin-plugins-data-public.isearchstart.aggs.md) + +## ISearchStart.aggs property + +agg config sub service [AggsStart](./kibana-plugin-plugins-data-public.aggsstart.md) + +Signature: + +```typescript +aggs: AggsStart; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.md new file mode 100644 index 0000000000000..cee213fc6e7e3 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchStart](./kibana-plugin-plugins-data-public.isearchstart.md) + +## ISearchStart interface + +search service + +Signature: + +```typescript +export interface ISearchStart +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [aggs](./kibana-plugin-plugins-data-public.isearchstart.aggs.md) | AggsStart | agg config sub service [AggsStart](./kibana-plugin-plugins-data-public.aggsstart.md) | +| [search](./kibana-plugin-plugins-data-public.isearchstart.search.md) | ISearchGeneric | low level search [ISearchGeneric](./kibana-plugin-plugins-data-public.isearchgeneric.md) | +| [searchSource](./kibana-plugin-plugins-data-public.isearchstart.searchsource.md) | ISearchStartSearchSource | high level search [ISearchStartSearchSource](./kibana-plugin-plugins-data-public.isearchstartsearchsource.md) | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.search.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.search.md new file mode 100644 index 0000000000000..80e140e9fdd5c --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.search.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchStart](./kibana-plugin-plugins-data-public.isearchstart.md) > [search](./kibana-plugin-plugins-data-public.isearchstart.search.md) + +## ISearchStart.search property + +low level search [ISearchGeneric](./kibana-plugin-plugins-data-public.isearchgeneric.md) + +Signature: + +```typescript +search: ISearchGeneric; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.searchsource.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.searchsource.md new file mode 100644 index 0000000000000..5d4b884b2c25b --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.searchsource.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchStart](./kibana-plugin-plugins-data-public.isearchstart.md) > [searchSource](./kibana-plugin-plugins-data-public.isearchstart.searchsource.md) + +## ISearchStart.searchSource property + +high level search [ISearchStartSearchSource](./kibana-plugin-plugins-data-public.isearchstartsearchsource.md) + +Signature: + +```typescript +searchSource: ISearchStartSearchSource; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstartsearchsource.create.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstartsearchsource.create.md new file mode 100644 index 0000000000000..7f6344b82d27c --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstartsearchsource.create.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchStartSearchSource](./kibana-plugin-plugins-data-public.isearchstartsearchsource.md) > [create](./kibana-plugin-plugins-data-public.isearchstartsearchsource.create.md) + +## ISearchStartSearchSource.create property + +creates [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) based on provided serialized [SearchSourceFields](./kibana-plugin-plugins-data-public.searchsourcefields.md) + +Signature: + +```typescript +create: (fields?: SearchSourceFields) => Promise; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstartsearchsource.createempty.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstartsearchsource.createempty.md new file mode 100644 index 0000000000000..b13b5d227c8b4 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstartsearchsource.createempty.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchStartSearchSource](./kibana-plugin-plugins-data-public.isearchstartsearchsource.md) > [createEmpty](./kibana-plugin-plugins-data-public.isearchstartsearchsource.createempty.md) + +## ISearchStartSearchSource.createEmpty property + +creates empty [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) + +Signature: + +```typescript +createEmpty: () => ISearchSource; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstartsearchsource.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstartsearchsource.md new file mode 100644 index 0000000000000..f10d5bb002a0f --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstartsearchsource.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchStartSearchSource](./kibana-plugin-plugins-data-public.isearchstartsearchsource.md) + +## ISearchStartSearchSource interface + +high level search service + +Signature: + +```typescript +export interface ISearchStartSearchSource +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [create](./kibana-plugin-plugins-data-public.isearchstartsearchsource.create.md) | (fields?: SearchSourceFields) => Promise<ISearchSource> | creates [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) based on provided serialized [SearchSourceFields](./kibana-plugin-plugins-data-public.searchsourcefields.md) | +| [createEmpty](./kibana-plugin-plugins-data-public.isearchstartsearchsource.createempty.md) | () => ISearchSource | creates empty [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md index 0c493ca492953..f51549c81fb62 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md @@ -8,6 +8,8 @@ | Class | Description | | --- | --- | +| [AggConfig](./kibana-plugin-plugins-data-public.aggconfig.md) | | +| [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) | | | [AggParamType](./kibana-plugin-plugins-data-public.aggparamtype.md) | | | [FieldFormat](./kibana-plugin-plugins-data-public.fieldformat.md) | | | [FilterManager](./kibana-plugin-plugins-data-public.filtermanager.md) | | @@ -18,6 +20,7 @@ | [Plugin](./kibana-plugin-plugins-data-public.plugin.md) | | | [RequestTimeoutError](./kibana-plugin-plugins-data-public.requesttimeouterror.md) | Class used to signify that a request timed out. Useful for applications to conditionally handle this type of error differently than other errors. | | [SearchInterceptor](./kibana-plugin-plugins-data-public.searchinterceptor.md) | | +| [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) | \* | | [TimeHistory](./kibana-plugin-plugins-data-public.timehistory.md) | | ## Enumerations @@ -47,8 +50,10 @@ | --- | --- | | [AggParamOption](./kibana-plugin-plugins-data-public.aggparamoption.md) | | | [ApplyGlobalFilterActionContext](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.md) | | -| [DataPublicPluginSetup](./kibana-plugin-plugins-data-public.datapublicpluginsetup.md) | | -| [DataPublicPluginStart](./kibana-plugin-plugins-data-public.datapublicpluginstart.md) | | +| [DataPublicPluginSetup](./kibana-plugin-plugins-data-public.datapublicpluginsetup.md) | Data plugin public Setup contract | +| [DataPublicPluginStart](./kibana-plugin-plugins-data-public.datapublicpluginstart.md) | Data plugin public Start contract | +| [DataPublicPluginStartActions](./kibana-plugin-plugins-data-public.datapublicpluginstartactions.md) | utilities to generate filters from action context | +| [DataPublicPluginStartUi](./kibana-plugin-plugins-data-public.datapublicpluginstartui.md) | Data plugin prewired UI components | | [EsQueryConfig](./kibana-plugin-plugins-data-public.esqueryconfig.md) | | | [FieldFormatConfig](./kibana-plugin-plugins-data-public.fieldformatconfig.md) | | | [FieldMappingSpec](./kibana-plugin-plugins-data-public.fieldmappingspec.md) | | @@ -65,6 +70,9 @@ | [IndexPatternAttributes](./kibana-plugin-plugins-data-public.indexpatternattributes.md) | Use data plugin interface instead | | [IndexPatternTypeMeta](./kibana-plugin-plugins-data-public.indexpatterntypemeta.md) | | | [ISearchOptions](./kibana-plugin-plugins-data-public.isearchoptions.md) | | +| [ISearchSetup](./kibana-plugin-plugins-data-public.isearchsetup.md) | The setup contract exposed by the Search plugin exposes the search strategy extension point. | +| [ISearchStart](./kibana-plugin-plugins-data-public.isearchstart.md) | search service | +| [ISearchStartSearchSource](./kibana-plugin-plugins-data-public.isearchstartsearchsource.md) | high level search service | | [KueryNode](./kibana-plugin-plugins-data-public.kuerynode.md) | | | [OptionedValueProp](./kibana-plugin-plugins-data-public.optionedvalueprop.md) | | | [Query](./kibana-plugin-plugins-data-public.query.md) | | @@ -79,7 +87,7 @@ | [SavedQueryService](./kibana-plugin-plugins-data-public.savedqueryservice.md) | | | [SearchError](./kibana-plugin-plugins-data-public.searcherror.md) | | | [SearchInterceptorDeps](./kibana-plugin-plugins-data-public.searchinterceptordeps.md) | | -| [SearchSourceFields](./kibana-plugin-plugins-data-public.searchsourcefields.md) | | +| [SearchSourceFields](./kibana-plugin-plugins-data-public.searchsourcefields.md) | search source fields | | [TabbedAggColumn](./kibana-plugin-plugins-data-public.tabbedaggcolumn.md) | \* | | [TabbedTable](./kibana-plugin-plugins-data-public.tabbedtable.md) | \* | | [TimeRange](./kibana-plugin-plugins-data-public.timerange.md) | | @@ -125,6 +133,8 @@ | [AggConfigOptions](./kibana-plugin-plugins-data-public.aggconfigoptions.md) | | | [AggGroupName](./kibana-plugin-plugins-data-public.agggroupname.md) | | | [AggParam](./kibana-plugin-plugins-data-public.aggparam.md) | | +| [AggsStart](./kibana-plugin-plugins-data-public.aggsstart.md) | AggsStart represents the actual external contract as AggsCommonStart is only used internally. The difference is that AggsStart includes the typings for the registry with initialized agg types. | +| [AutocompleteStart](./kibana-plugin-plugins-data-public.autocompletestart.md) | \* | | [CustomFilter](./kibana-plugin-plugins-data-public.customfilter.md) | | | [EsaggsExpressionFunctionDefinition](./kibana-plugin-plugins-data-public.esaggsexpressionfunctiondefinition.md) | | | [EsdslExpressionFunctionDefinition](./kibana-plugin-plugins-data-public.esdslexpressionfunctiondefinition.md) | | @@ -134,6 +144,7 @@ | [FieldFormatId](./kibana-plugin-plugins-data-public.fieldformatid.md) | id type is needed for creating custom converters. | | [FieldFormatsContentType](./kibana-plugin-plugins-data-public.fieldformatscontenttype.md) | \* | | [FieldFormatsGetConfigFn](./kibana-plugin-plugins-data-public.fieldformatsgetconfigfn.md) | | +| [FieldFormatsStart](./kibana-plugin-plugins-data-public.fieldformatsstart.md) | | | [IAggConfig](./kibana-plugin-plugins-data-public.iaggconfig.md) | AggConfig This class represents an aggregation, which is displayed in the left-hand nav of the Visualize app. | | [IAggType](./kibana-plugin-plugins-data-public.iaggtype.md) | | | [IFieldFormat](./kibana-plugin-plugins-data-public.ifieldformat.md) | | @@ -145,12 +156,13 @@ | [InputTimeRange](./kibana-plugin-plugins-data-public.inputtimerange.md) | | | [ISearch](./kibana-plugin-plugins-data-public.isearch.md) | | | [ISearchGeneric](./kibana-plugin-plugins-data-public.isearchgeneric.md) | | -| [ISearchSource](./kibana-plugin-plugins-data-public.isearchsource.md) | \* | +| [ISearchSource](./kibana-plugin-plugins-data-public.isearchsource.md) | search source interface | | [MappingObject](./kibana-plugin-plugins-data-public.mappingobject.md) | | | [MatchAllFilter](./kibana-plugin-plugins-data-public.matchallfilter.md) | | | [ParsedInterval](./kibana-plugin-plugins-data-public.parsedinterval.md) | | | [PhraseFilter](./kibana-plugin-plugins-data-public.phrasefilter.md) | | | [PhrasesFilter](./kibana-plugin-plugins-data-public.phrasesfilter.md) | | +| [QueryStart](./kibana-plugin-plugins-data-public.querystart.md) | | | [QuerySuggestion](./kibana-plugin-plugins-data-public.querysuggestion.md) | \* | | [QuerySuggestionGetFn](./kibana-plugin-plugins-data-public.querysuggestiongetfn.md) | | | [RangeFilter](./kibana-plugin-plugins-data-public.rangefilter.md) | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystart.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystart.md new file mode 100644 index 0000000000000..f48a9ee7a79e4 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystart.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [QueryStart](./kibana-plugin-plugins-data-public.querystart.md) + +## QueryStart type + +Signature: + +```typescript +export declare type QueryStart = ReturnType; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.getpendingcount_.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.getpendingcount_.md deleted file mode 100644 index ef36b3f37b0c7..0000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.getpendingcount_.md +++ /dev/null @@ -1,17 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchInterceptor](./kibana-plugin-plugins-data-public.searchinterceptor.md) > [getPendingCount$](./kibana-plugin-plugins-data-public.searchinterceptor.getpendingcount_.md) - -## SearchInterceptor.getPendingCount$() method - -Returns an `Observable` over the current number of pending searches. This could mean that one of the search requests is still in flight, or that it has only received partial responses. - -Signature: - -```typescript -getPendingCount$(): Observable; -``` -Returns: - -`Observable` - diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md index fd9f23a7f0052..5cee345db6cd2 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md @@ -21,11 +21,11 @@ export declare class SearchInterceptor | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [deps](./kibana-plugin-plugins-data-public.searchinterceptor.deps.md) | | SearchInterceptorDeps | | +| [showTimeoutError](./kibana-plugin-plugins-data-public.searchinterceptor.showtimeouterror.md) | | ((e: Error) => void) & import("lodash").Cancelable | | ## Methods | Method | Modifiers | Description | | --- | --- | --- | -| [getPendingCount$()](./kibana-plugin-plugins-data-public.searchinterceptor.getpendingcount_.md) | | Returns an Observable over the current number of pending searches. This could mean that one of the search requests is still in flight, or that it has only received partial responses. | | [search(request, options)](./kibana-plugin-plugins-data-public.searchinterceptor.search.md) | | Searches using the given search method. Overrides the AbortSignal with one that will abort either when cancelPending is called, when the request times out, or when the original AbortSignal is aborted. Updates pendingCount$ when the request is started/finalized. | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.showtimeouterror.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.showtimeouterror.md new file mode 100644 index 0000000000000..91ecb2821acbf --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.showtimeouterror.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchInterceptor](./kibana-plugin-plugins-data-public.searchinterceptor.md) > [showTimeoutError](./kibana-plugin-plugins-data-public.searchinterceptor.showtimeouterror.md) + +## SearchInterceptor.showTimeoutError property + +Signature: + +```typescript +protected showTimeoutError: ((e: Error) => void) & import("lodash").Cancelable; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource._constructor_.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource._constructor_.md new file mode 100644 index 0000000000000..00e9050ee8ff9 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource._constructor_.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [(constructor)](./kibana-plugin-plugins-data-public.searchsource._constructor_.md) + +## SearchSource.(constructor) + +Constructs a new instance of the `SearchSource` class + +Signature: + +```typescript +constructor(fields: SearchSourceFields | undefined, dependencies: SearchSourceDependencies); +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| fields | SearchSourceFields | undefined | | +| dependencies | SearchSourceDependencies | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.create.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.create.md new file mode 100644 index 0000000000000..4264c3ff224b1 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.create.md @@ -0,0 +1,20 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [create](./kibana-plugin-plugins-data-public.searchsource.create.md) + +## SearchSource.create() method + +> Warning: This API is now obsolete. +> +> Don't use. +> + +Signature: + +```typescript +create(): SearchSource; +``` +Returns: + +`SearchSource` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.createchild.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.createchild.md new file mode 100644 index 0000000000000..0c2e75651b354 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.createchild.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [createChild](./kibana-plugin-plugins-data-public.searchsource.createchild.md) + +## SearchSource.createChild() method + +creates a new child search source + +Signature: + +```typescript +createChild(options?: {}): SearchSource; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| options | {} | | + +Returns: + +`SearchSource` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.createcopy.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.createcopy.md new file mode 100644 index 0000000000000..1053d31010d00 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.createcopy.md @@ -0,0 +1,17 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [createCopy](./kibana-plugin-plugins-data-public.searchsource.createcopy.md) + +## SearchSource.createCopy() method + +creates a copy of this search source (without its children) + +Signature: + +```typescript +createCopy(): SearchSource; +``` +Returns: + +`SearchSource` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.destroy.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.destroy.md new file mode 100644 index 0000000000000..8a7cc5ee75d11 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.destroy.md @@ -0,0 +1,17 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [destroy](./kibana-plugin-plugins-data-public.searchsource.destroy.md) + +## SearchSource.destroy() method + +Completely destroy the SearchSource. {undefined} + +Signature: + +```typescript +destroy(): void; +``` +Returns: + +`void` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.fetch.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.fetch.md new file mode 100644 index 0000000000000..8fd17e6b1a1d9 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.fetch.md @@ -0,0 +1,25 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [fetch](./kibana-plugin-plugins-data-public.searchsource.fetch.md) + +## SearchSource.fetch() method + +Fetch this source and reject the returned Promise on error + + +Signature: + +```typescript +fetch(options?: ISearchOptions): Promise>; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| options | ISearchOptions | | + +Returns: + +`Promise>` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getfield.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getfield.md new file mode 100644 index 0000000000000..7c516cc29df15 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getfield.md @@ -0,0 +1,25 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [getField](./kibana-plugin-plugins-data-public.searchsource.getfield.md) + +## SearchSource.getField() method + +Gets a single field from the fields + +Signature: + +```typescript +getField(field: K, recurse?: boolean): SearchSourceFields[K]; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| field | K | | +| recurse | boolean | | + +Returns: + +`SearchSourceFields[K]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getfields.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getfields.md new file mode 100644 index 0000000000000..1980227bee623 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getfields.md @@ -0,0 +1,51 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [getFields](./kibana-plugin-plugins-data-public.searchsource.getfields.md) + +## SearchSource.getFields() method + +returns all search source fields + +Signature: + +```typescript +getFields(): { + type?: string | undefined; + query?: import("../..").Query | undefined; + filter?: Filter | Filter[] | (() => Filter | Filter[] | undefined) | undefined; + sort?: Record | Record[] | undefined; + highlight?: any; + highlightAll?: boolean | undefined; + aggs?: any; + from?: number | undefined; + size?: number | undefined; + source?: string | boolean | string[] | undefined; + version?: boolean | undefined; + fields?: string | boolean | string[] | undefined; + index?: import("../..").IndexPattern | undefined; + searchAfter?: import("./types").EsQuerySearchAfter | undefined; + timeout?: string | undefined; + terminate_after?: number | undefined; + }; +``` +Returns: + +`{ + type?: string | undefined; + query?: import("../..").Query | undefined; + filter?: Filter | Filter[] | (() => Filter | Filter[] | undefined) | undefined; + sort?: Record | Record[] | undefined; + highlight?: any; + highlightAll?: boolean | undefined; + aggs?: any; + from?: number | undefined; + size?: number | undefined; + source?: string | boolean | string[] | undefined; + version?: boolean | undefined; + fields?: string | boolean | string[] | undefined; + index?: import("../..").IndexPattern | undefined; + searchAfter?: import("./types").EsQuerySearchAfter | undefined; + timeout?: string | undefined; + terminate_after?: number | undefined; + }` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getid.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getid.md new file mode 100644 index 0000000000000..b33410d86ae85 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getid.md @@ -0,0 +1,17 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [getId](./kibana-plugin-plugins-data-public.searchsource.getid.md) + +## SearchSource.getId() method + +returns search source id + +Signature: + +```typescript +getId(): string; +``` +Returns: + +`string` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getownfield.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getownfield.md new file mode 100644 index 0000000000000..d5a133772264e --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getownfield.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [getOwnField](./kibana-plugin-plugins-data-public.searchsource.getownfield.md) + +## SearchSource.getOwnField() method + +Get the field from our own fields, don't traverse up the chain + +Signature: + +```typescript +getOwnField(field: K): SearchSourceFields[K]; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| field | K | | + +Returns: + +`SearchSourceFields[K]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getparent.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getparent.md new file mode 100644 index 0000000000000..14578f7949ba6 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getparent.md @@ -0,0 +1,17 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [getParent](./kibana-plugin-plugins-data-public.searchsource.getparent.md) + +## SearchSource.getParent() method + +Get the parent of this SearchSource {undefined\|searchSource} + +Signature: + +```typescript +getParent(): SearchSource | undefined; +``` +Returns: + +`SearchSource | undefined` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getsearchrequestbody.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getsearchrequestbody.md new file mode 100644 index 0000000000000..cc50d3f017971 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getsearchrequestbody.md @@ -0,0 +1,17 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [getSearchRequestBody](./kibana-plugin-plugins-data-public.searchsource.getsearchrequestbody.md) + +## SearchSource.getSearchRequestBody() method + +Returns body contents of the search request, often referred as query DSL. + +Signature: + +```typescript +getSearchRequestBody(): Promise; +``` +Returns: + +`Promise` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getserializedfields.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getserializedfields.md new file mode 100644 index 0000000000000..3f58a76b24cd0 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.getserializedfields.md @@ -0,0 +1,17 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [getSerializedFields](./kibana-plugin-plugins-data-public.searchsource.getserializedfields.md) + +## SearchSource.getSerializedFields() method + +serializes search source fields (which can later be passed to [ISearchStartSearchSource](./kibana-plugin-plugins-data-public.isearchstartsearchsource.md)) + +Signature: + +```typescript +getSerializedFields(): SearchSourceFields; +``` +Returns: + +`SearchSourceFields` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.history.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.history.md new file mode 100644 index 0000000000000..e77c9dac7239f --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.history.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [history](./kibana-plugin-plugins-data-public.searchsource.history.md) + +## SearchSource.history property + +Signature: + +```typescript +history: SearchRequest[]; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.md new file mode 100644 index 0000000000000..87346f81b13e2 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.md @@ -0,0 +1,49 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) + +## SearchSource class + +\* + +Signature: + +```typescript +export declare class SearchSource +``` + +## Constructors + +| Constructor | Modifiers | Description | +| --- | --- | --- | +| [(constructor)(fields, dependencies)](./kibana-plugin-plugins-data-public.searchsource._constructor_.md) | | Constructs a new instance of the SearchSource class | + +## Properties + +| Property | Modifiers | Type | Description | +| --- | --- | --- | --- | +| [history](./kibana-plugin-plugins-data-public.searchsource.history.md) | | SearchRequest[] | | + +## Methods + +| Method | Modifiers | Description | +| --- | --- | --- | +| [create()](./kibana-plugin-plugins-data-public.searchsource.create.md) | | | +| [createChild(options)](./kibana-plugin-plugins-data-public.searchsource.createchild.md) | | creates a new child search source | +| [createCopy()](./kibana-plugin-plugins-data-public.searchsource.createcopy.md) | | creates a copy of this search source (without its children) | +| [destroy()](./kibana-plugin-plugins-data-public.searchsource.destroy.md) | | Completely destroy the SearchSource. {undefined} | +| [fetch(options)](./kibana-plugin-plugins-data-public.searchsource.fetch.md) | | Fetch this source and reject the returned Promise on error | +| [getField(field, recurse)](./kibana-plugin-plugins-data-public.searchsource.getfield.md) | | Gets a single field from the fields | +| [getFields()](./kibana-plugin-plugins-data-public.searchsource.getfields.md) | | returns all search source fields | +| [getId()](./kibana-plugin-plugins-data-public.searchsource.getid.md) | | returns search source id | +| [getOwnField(field)](./kibana-plugin-plugins-data-public.searchsource.getownfield.md) | | Get the field from our own fields, don't traverse up the chain | +| [getParent()](./kibana-plugin-plugins-data-public.searchsource.getparent.md) | | Get the parent of this SearchSource {undefined\|searchSource} | +| [getSearchRequestBody()](./kibana-plugin-plugins-data-public.searchsource.getsearchrequestbody.md) | | Returns body contents of the search request, often referred as query DSL. | +| [getSerializedFields()](./kibana-plugin-plugins-data-public.searchsource.getserializedfields.md) | | serializes search source fields (which can later be passed to [ISearchStartSearchSource](./kibana-plugin-plugins-data-public.isearchstartsearchsource.md)) | +| [onRequestStart(handler)](./kibana-plugin-plugins-data-public.searchsource.onrequeststart.md) | | Add a handler that will be notified whenever requests start | +| [serialize()](./kibana-plugin-plugins-data-public.searchsource.serialize.md) | | Serializes the instance to a JSON string and a set of referenced objects. Use this method to get a representation of the search source which can be stored in a saved object.The references returned by this function can be mixed with other references in the same object, however make sure there are no name-collisions. The references will be named kibanaSavedObjectMeta.searchSourceJSON.index and kibanaSavedObjectMeta.searchSourceJSON.filter[<number>].meta.index.Using createSearchSource, the instance can be re-created. | +| [setField(field, value)](./kibana-plugin-plugins-data-public.searchsource.setfield.md) | | sets value to a single search source feild | +| [setFields(newFields)](./kibana-plugin-plugins-data-public.searchsource.setfields.md) | | Internal, do not use. Overrides all search source fields with the new field array. | +| [setParent(parent, options)](./kibana-plugin-plugins-data-public.searchsource.setparent.md) | | Set a searchSource that this source should inherit from | +| [setPreferredSearchStrategyId(searchStrategyId)](./kibana-plugin-plugins-data-public.searchsource.setpreferredsearchstrategyid.md) | | internal, dont use | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.onrequeststart.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.onrequeststart.md new file mode 100644 index 0000000000000..a9386ddae44e1 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.onrequeststart.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [onRequestStart](./kibana-plugin-plugins-data-public.searchsource.onrequeststart.md) + +## SearchSource.onRequestStart() method + +Add a handler that will be notified whenever requests start + +Signature: + +```typescript +onRequestStart(handler: (searchSource: SearchSource, options?: ISearchOptions) => Promise): void; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| handler | (searchSource: SearchSource, options?: ISearchOptions) => Promise<unknown> | | + +Returns: + +`void` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.serialize.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.serialize.md new file mode 100644 index 0000000000000..73ba8eb66040b --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.serialize.md @@ -0,0 +1,27 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [serialize](./kibana-plugin-plugins-data-public.searchsource.serialize.md) + +## SearchSource.serialize() method + +Serializes the instance to a JSON string and a set of referenced objects. Use this method to get a representation of the search source which can be stored in a saved object. + +The references returned by this function can be mixed with other references in the same object, however make sure there are no name-collisions. The references will be named `kibanaSavedObjectMeta.searchSourceJSON.index` and `kibanaSavedObjectMeta.searchSourceJSON.filter[].meta.index`. + +Using `createSearchSource`, the instance can be re-created. + +Signature: + +```typescript +serialize(): { + searchSourceJSON: string; + references: import("../../../../../core/public").SavedObjectReference[]; + }; +``` +Returns: + +`{ + searchSourceJSON: string; + references: import("../../../../../core/public").SavedObjectReference[]; + }` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setfield.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setfield.md new file mode 100644 index 0000000000000..22619940f1589 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setfield.md @@ -0,0 +1,25 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [setField](./kibana-plugin-plugins-data-public.searchsource.setfield.md) + +## SearchSource.setField() method + +sets value to a single search source feild + +Signature: + +```typescript +setField(field: K, value: SearchSourceFields[K]): this; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| field | K | | +| value | SearchSourceFields[K] | | + +Returns: + +`this` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setfields.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setfields.md new file mode 100644 index 0000000000000..f92ffc0fc991d --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setfields.md @@ -0,0 +1,25 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [setFields](./kibana-plugin-plugins-data-public.searchsource.setfields.md) + +## SearchSource.setFields() method + +Internal, do not use. Overrides all search source fields with the new field array. + + +Signature: + +```typescript +setFields(newFields: SearchSourceFields): this; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| newFields | SearchSourceFields | | + +Returns: + +`this` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setparent.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setparent.md new file mode 100644 index 0000000000000..19bf10bec210f --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setparent.md @@ -0,0 +1,25 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [setParent](./kibana-plugin-plugins-data-public.searchsource.setparent.md) + +## SearchSource.setParent() method + +Set a searchSource that this source should inherit from + +Signature: + +```typescript +setParent(parent?: ISearchSource, options?: SearchSourceOptions): this; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| parent | ISearchSource | | +| options | SearchSourceOptions | | + +Returns: + +`this` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setpreferredsearchstrategyid.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setpreferredsearchstrategyid.md new file mode 100644 index 0000000000000..e3261873ba104 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsource.setpreferredsearchstrategyid.md @@ -0,0 +1,24 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) > [setPreferredSearchStrategyId](./kibana-plugin-plugins-data-public.searchsource.setpreferredsearchstrategyid.md) + +## SearchSource.setPreferredSearchStrategyId() method + +internal, dont use + +Signature: + +```typescript +setPreferredSearchStrategyId(searchStrategyId: string): void; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| searchStrategyId | string | | + +Returns: + +`void` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.aggs.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.aggs.md index 743646708b4c6..f6bab8e424857 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.aggs.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.aggs.md @@ -4,6 +4,8 @@ ## SearchSourceFields.aggs property +[AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) + Signature: ```typescript diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.filter.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.filter.md index a14d33420a22d..5fd615cc647d2 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.filter.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.filter.md @@ -4,6 +4,8 @@ ## SearchSourceFields.filter property +[Filter](./kibana-plugin-plugins-data-public.filter.md) + Signature: ```typescript diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.index.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.index.md index fa1d1a552a560..cf1b1cfa253fd 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.index.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.index.md @@ -4,6 +4,7 @@ ## SearchSourceFields.index property + Signature: ```typescript diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.md index 7a64af0f8b2b8..d19f1da439cee 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.md @@ -4,6 +4,8 @@ ## SearchSourceFields interface +search source fields + Signature: ```typescript @@ -14,17 +16,17 @@ export interface SearchSourceFields | Property | Type | Description | | --- | --- | --- | -| [aggs](./kibana-plugin-plugins-data-public.searchsourcefields.aggs.md) | any | | +| [aggs](./kibana-plugin-plugins-data-public.searchsourcefields.aggs.md) | any | [AggConfigs](./kibana-plugin-plugins-data-public.aggconfigs.md) | | [fields](./kibana-plugin-plugins-data-public.searchsourcefields.fields.md) | NameList | | -| [filter](./kibana-plugin-plugins-data-public.searchsourcefields.filter.md) | Filter[] | Filter | (() => Filter[] | Filter | undefined) | | +| [filter](./kibana-plugin-plugins-data-public.searchsourcefields.filter.md) | Filter[] | Filter | (() => Filter[] | Filter | undefined) | [Filter](./kibana-plugin-plugins-data-public.filter.md) | | [from](./kibana-plugin-plugins-data-public.searchsourcefields.from.md) | number | | | [highlight](./kibana-plugin-plugins-data-public.searchsourcefields.highlight.md) | any | | | [highlightAll](./kibana-plugin-plugins-data-public.searchsourcefields.highlightall.md) | boolean | | | [index](./kibana-plugin-plugins-data-public.searchsourcefields.index.md) | IndexPattern | | -| [query](./kibana-plugin-plugins-data-public.searchsourcefields.query.md) | Query | | +| [query](./kibana-plugin-plugins-data-public.searchsourcefields.query.md) | Query | [Query](./kibana-plugin-plugins-data-public.query.md) | | [searchAfter](./kibana-plugin-plugins-data-public.searchsourcefields.searchafter.md) | EsQuerySearchAfter | | | [size](./kibana-plugin-plugins-data-public.searchsourcefields.size.md) | number | | -| [sort](./kibana-plugin-plugins-data-public.searchsourcefields.sort.md) | EsQuerySortValue | EsQuerySortValue[] | | +| [sort](./kibana-plugin-plugins-data-public.searchsourcefields.sort.md) | EsQuerySortValue | EsQuerySortValue[] | [EsQuerySortValue](./kibana-plugin-plugins-data-public.esquerysortvalue.md) | | [source](./kibana-plugin-plugins-data-public.searchsourcefields.source.md) | NameList | | | [terminate\_after](./kibana-plugin-plugins-data-public.searchsourcefields.terminate_after.md) | number | | | [timeout](./kibana-plugin-plugins-data-public.searchsourcefields.timeout.md) | string | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.query.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.query.md index 687dafce798d1..661ce94a06afb 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.query.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.query.md @@ -4,6 +4,8 @@ ## SearchSourceFields.query property +[Query](./kibana-plugin-plugins-data-public.query.md) + Signature: ```typescript diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.sort.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.sort.md index c10f556cef6d6..32f513378e35e 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.sort.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchsourcefields.sort.md @@ -4,6 +4,8 @@ ## SearchSourceFields.sort property +[EsQuerySortValue](./kibana-plugin-plugins-data-public.esquerysortvalue.md) + Signature: ```typescript diff --git a/packages/kbn-config-schema/package.json b/packages/kbn-config-schema/package.json index 10b1741d98441..9abe7f31dd060 100644 --- a/packages/kbn-config-schema/package.json +++ b/packages/kbn-config-schema/package.json @@ -11,7 +11,7 @@ }, "devDependencies": { "typescript": "4.0.2", - "tsd": "^0.7.4" + "tsd": "^0.13.1" }, "peerDependencies": { "lodash": "^4.17.15", diff --git a/packages/kbn-utility-types/package.json b/packages/kbn-utility-types/package.json index a999eb41eb781..d1d7a1c0397cf 100644 --- a/packages/kbn-utility-types/package.json +++ b/packages/kbn-utility-types/package.json @@ -16,7 +16,7 @@ "utility-types": "^3.10.0" }, "devDependencies": { - "del-cli": "^3.0.0", - "tsd": "^0.7.4" + "del-cli": "^3.0.1", + "tsd": "^0.13.1" } } diff --git a/packages/kbn-utility-types/test-d/union_to_intersection.ts b/packages/kbn-utility-types/test-d/union_to_intersection.ts index ba385268475e7..8b49436bdd953 100644 --- a/packages/kbn-utility-types/test-d/union_to_intersection.ts +++ b/packages/kbn-utility-types/test-d/union_to_intersection.ts @@ -17,12 +17,12 @@ * under the License. */ -import { expectType } from 'tsd'; +import { expectAssignable } from 'tsd'; import { UnionToIntersection } from '../index'; type INTERSECTED = UnionToIntersection<{ foo: 'bar' } | { baz: 'qux' }>; -expectType({ +expectAssignable({ foo: 'bar', baz: 'qux', }); diff --git a/packages/kbn-utility-types/test-d/unwrap_observable.ts b/packages/kbn-utility-types/test-d/unwrap_observable.ts index af4fa9abf6ec7..e9791cfd36beb 100644 --- a/packages/kbn-utility-types/test-d/unwrap_observable.ts +++ b/packages/kbn-utility-types/test-d/unwrap_observable.ts @@ -17,9 +17,9 @@ * under the License. */ -import { expectType } from 'tsd'; +import { expectAssignable } from 'tsd'; import { UnwrapObservable, ObservableLike } from '../index'; type STRING = UnwrapObservable>; -expectType('adf'); +expectAssignable('adf'); diff --git a/packages/kbn-utility-types/test-d/unwrap_promise.ts b/packages/kbn-utility-types/test-d/unwrap_promise.ts index 9c4b1bc76b805..b61b24e4b3f15 100644 --- a/packages/kbn-utility-types/test-d/unwrap_promise.ts +++ b/packages/kbn-utility-types/test-d/unwrap_promise.ts @@ -17,11 +17,11 @@ * under the License. */ -import { expectType } from 'tsd'; +import { expectAssignable } from 'tsd'; import { UnwrapPromise } from '../index'; type STRING = UnwrapPromise>; type TUPLE = UnwrapPromise>; -expectType('adf'); -expectType([1, 2]); +expectAssignable('adf'); +expectAssignable([1, 2]); diff --git a/packages/kbn-utility-types/test-d/values.ts b/packages/kbn-utility-types/test-d/values.ts index 9e50cfebde1db..69bee9c3c9655 100644 --- a/packages/kbn-utility-types/test-d/values.ts +++ b/packages/kbn-utility-types/test-d/values.ts @@ -17,22 +17,22 @@ * under the License. */ -import { expectType } from 'tsd'; +import { expectAssignable } from 'tsd'; import { Values } from '../index'; // Arrays type STRING = Values; type ASDF_FOO = Values>; -expectType('adf'); -expectType('asdf'); -expectType('foo'); +expectAssignable('adf'); +expectAssignable('asdf'); +expectAssignable('foo'); // Objects type STRING2 = Values>; type FOO = Values>; type BAR = Values<{ foo: 'bar' }>; -expectType('adf'); -expectType('foo'); -expectType('bar'); +expectAssignable('adf'); +expectAssignable('foo'); +expectAssignable('bar'); diff --git a/src/core/MIGRATION.md b/src/core/MIGRATION.md index ea0e8d66d58f2..c6320e42655a2 100644 --- a/src/core/MIGRATION.md +++ b/src/core/MIGRATION.md @@ -1231,7 +1231,7 @@ import { npStart: { plugins } } from 'ui/new_platform'; | `import 'ui/filter_bar'` | `import { FilterBar } from '../data/public'` | Directive is deprecated. | | `import 'ui/query_bar'` | `import { QueryStringInput } from '../data/public'` | Directives are deprecated. | | `import 'ui/search_bar'` | `import { SearchBar } from '../data/public'` | Directive is deprecated. | -| `import 'ui/kbn_top_nav'` | `import { TopNavMenu } from '../navigation/public'` | Directive was moved to `src/plugins/kibana_legacy`. | +| `import 'ui/kbn_top_nav'` | `import { TopNavMenu } from '../navigation/public'` | Directive was removed. | | `ui/saved_objects/components/saved_object_finder` | `import { SavedObjectFinder } from '../saved_objects/public'` | | | `core_plugins/interpreter` | `plugins.data.expressions` | | `ui/courier` | `plugins.data.search` | diff --git a/src/core/server/index.ts b/src/core/server/index.ts index 97aca74bfd48f..d127471348d9f 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -293,6 +293,7 @@ export { SavedObjectsTypeManagementDefinition, SavedObjectMigrationMap, SavedObjectMigrationFn, + SavedObjectsUtils, exportSavedObjectsToStream, importSavedObjectsFromStream, resolveSavedObjectsImportErrors, diff --git a/src/core/server/plugins/discovery/plugin_manifest_parser.test.ts b/src/core/server/plugins/discovery/plugin_manifest_parser.test.ts index 64d1256be2f30..836aabf881474 100644 --- a/src/core/server/plugins/discovery/plugin_manifest_parser.test.ts +++ b/src/core/server/plugins/discovery/plugin_manifest_parser.test.ts @@ -116,6 +116,16 @@ test('logs warning if pluginId is not in camelCase format', async () => { `); }); +test('does not log pluginId format warning in dist mode', async () => { + mockReadFile.mockImplementation((path, cb) => { + cb(null, Buffer.from(JSON.stringify({ id: 'some_name', version: 'kibana', server: true }))); + }); + + expect(loggingSystemMock.collect(logger).warn).toHaveLength(0); + await parseManifest(pluginPath, { ...packageInfo, dist: true }, logger); + expect(loggingSystemMock.collect(logger).warn.length).toBe(0); +}); + test('return error when plugin version is missing', async () => { mockReadFile.mockImplementation((path, cb) => { cb(null, Buffer.from(JSON.stringify({ id: 'someId' }))); diff --git a/src/core/server/plugins/discovery/plugin_manifest_parser.ts b/src/core/server/plugins/discovery/plugin_manifest_parser.ts index 0d33e266c37db..cfc412cb60b50 100644 --- a/src/core/server/plugins/discovery/plugin_manifest_parser.ts +++ b/src/core/server/plugins/discovery/plugin_manifest_parser.ts @@ -116,7 +116,7 @@ export async function parseManifest( ); } - if (!isCamelCase(manifest.id)) { + if (!packageInfo.dist && !isCamelCase(manifest.id)) { log.warn(`Expect plugin "id" in camelCase, but found: ${manifest.id}`); } diff --git a/src/core/server/saved_objects/routes/bulk_update.ts b/src/core/server/saved_objects/routes/bulk_update.ts index c112833b29f3f..882213644146a 100644 --- a/src/core/server/saved_objects/routes/bulk_update.ts +++ b/src/core/server/saved_objects/routes/bulk_update.ts @@ -40,6 +40,7 @@ export const registerBulkUpdateRoute = (router: IRouter) => { }) ) ), + namespace: schema.maybe(schema.string({ minLength: 1 })), }) ), }, diff --git a/src/core/server/saved_objects/service/index.ts b/src/core/server/saved_objects/service/index.ts index 271d4dd67d43e..c33a9f2f3b157 100644 --- a/src/core/server/saved_objects/service/index.ts +++ b/src/core/server/saved_objects/service/index.ts @@ -27,6 +27,7 @@ export { SavedObjectsErrorHelpers, SavedObjectsClientFactory, SavedObjectsClientFactoryProvider, + SavedObjectsUtils, } from './lib'; export * from './saved_objects_client'; diff --git a/src/core/server/saved_objects/service/lib/index.ts b/src/core/server/saved_objects/service/lib/index.ts index e103120388e35..eae8c5ef2e10c 100644 --- a/src/core/server/saved_objects/service/lib/index.ts +++ b/src/core/server/saved_objects/service/lib/index.ts @@ -30,3 +30,5 @@ export { } from './scoped_client_provider'; export { SavedObjectsErrorHelpers } from './errors'; + +export { SavedObjectsUtils } from './utils'; diff --git a/src/core/server/saved_objects/service/lib/repository.test.js b/src/core/server/saved_objects/service/lib/repository.test.js index f2e3b3e633cd6..7d30875b90796 100644 --- a/src/core/server/saved_objects/service/lib/repository.test.js +++ b/src/core/server/saved_objects/service/lib/repository.test.js @@ -155,27 +155,33 @@ describe('SavedObjectsRepository', () => { log: {}, }); - const getMockGetResponse = ({ type, id, references, namespace, originId }) => ({ - // NOTE: Elasticsearch returns more fields (_index, _type) but the SavedObjectsRepository method ignores these - found: true, - _id: `${registry.isSingleNamespace(type) && namespace ? `${namespace}:` : ''}${type}:${id}`, - ...mockVersionProps, - _source: { - ...(registry.isSingleNamespace(type) && { namespace }), - ...(registry.isMultiNamespace(type) && { namespaces: [namespace ?? 'default'] }), - ...(originId && { originId }), - type, - [type]: { title: 'Testing' }, - references, - specialProperty: 'specialValue', - ...mockTimestampFields, - }, - }); + const getMockGetResponse = ( + { type, id, references, namespace: objectNamespace, originId }, + namespace + ) => { + const namespaceId = objectNamespace === 'default' ? undefined : objectNamespace ?? namespace; + return { + // NOTE: Elasticsearch returns more fields (_index, _type) but the SavedObjectsRepository method ignores these + found: true, + _id: `${ + registry.isSingleNamespace(type) && namespaceId ? `${namespaceId}:` : '' + }${type}:${id}`, + ...mockVersionProps, + _source: { + ...(registry.isSingleNamespace(type) && { namespace: namespaceId }), + ...(registry.isMultiNamespace(type) && { namespaces: [namespaceId ?? 'default'] }), + ...(originId && { originId }), + type, + [type]: { title: 'Testing' }, + references, + specialProperty: 'specialValue', + ...mockTimestampFields, + }, + }; + }; const getMockMgetResponse = (objects, namespace) => ({ - docs: objects.map((obj) => - obj.found === false ? obj : getMockGetResponse({ ...obj, namespace }) - ), + docs: objects.map((obj) => (obj.found === false ? obj : getMockGetResponse(obj, namespace))), }); expect.extend({ @@ -586,6 +592,16 @@ describe('SavedObjectsRepository', () => { ); }); + it(`normalizes options.namespace from 'default' to undefined`, async () => { + await bulkCreateSuccess([obj1, obj2], { namespace: 'default' }); + const expected = expect.not.objectContaining({ namespace: 'default' }); + const body = [expect.any(Object), expected, expect.any(Object), expected]; + expect(client.bulk).toHaveBeenCalledWith( + expect.objectContaining({ body }), + expect.anything() + ); + }); + it(`doesn't add namespace to request body for any types that are not single-namespace`, async () => { const objects = [ { ...obj1, type: NAMESPACE_AGNOSTIC_TYPE }, @@ -653,19 +669,19 @@ describe('SavedObjectsRepository', () => { }); it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { - const getId = (type, id) => `${namespace}:${type}:${id}`; + const getId = (type, id) => `${namespace}:${type}:${id}`; // test that the raw document ID equals this (e.g., has a namespace prefix) await bulkCreateSuccess([obj1, obj2], { namespace }); expectClientCallArgsAction([obj1, obj2], { method: 'create', getId }); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { - const getId = (type, id) => `${type}:${id}`; + const getId = (type, id) => `${type}:${id}`; // test that the raw document ID equals this (e.g., does not have a namespace prefix) await bulkCreateSuccess([obj1, obj2]); expectClientCallArgsAction([obj1, obj2], { method: 'create', getId }); }); it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { - const getId = (type, id) => `${type}:${id}`; + const getId = (type, id) => `${type}:${id}`; // test that the raw document ID equals this (e.g., does not have a namespace prefix) const objects = [ { ...obj1, type: NAMESPACE_AGNOSTIC_TYPE }, { ...obj2, type: MULTI_NAMESPACE_TYPE }, @@ -972,19 +988,25 @@ describe('SavedObjectsRepository', () => { describe('client calls', () => { it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { - const getId = (type, id) => `${namespace}:${type}:${id}`; + const getId = (type, id) => `${namespace}:${type}:${id}`; // test that the raw document ID equals this (e.g., has a namespace prefix) await bulkGetSuccess([obj1, obj2], { namespace }); _expectClientCallArgs([obj1, obj2], { getId }); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { - const getId = (type, id) => `${type}:${id}`; + const getId = (type, id) => `${type}:${id}`; // test that the raw document ID equals this (e.g., does not have a namespace prefix) await bulkGetSuccess([obj1, obj2]); _expectClientCallArgs([obj1, obj2], { getId }); }); + it(`normalizes options.namespace from 'default' to undefined`, async () => { + const getId = (type, id) => `${type}:${id}`; // test that the raw document ID equals this (e.g., does not have a namespace prefix) + await bulkGetSuccess([obj1, obj2], { namespace: 'default' }); + _expectClientCallArgs([obj1, obj2], { getId }); + }); + it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { - const getId = (type, id) => `${type}:${id}`; + const getId = (type, id) => `${type}:${id}`; // test that the raw document ID equals this (e.g., does not have a namespace prefix) let objects = [obj1, obj2].map((obj) => ({ ...obj, type: NAMESPACE_AGNOSTIC_TYPE })); await bulkGetSuccess(objects, { namespace }); _expectClientCallArgs(objects, { getId }); @@ -1327,32 +1349,66 @@ describe('SavedObjectsRepository', () => { }); it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { - const getId = (type, id) => `${namespace}:${type}:${id}`; + const getId = (type, id) => `${namespace}:${type}:${id}`; // test that the raw document ID equals this (e.g., has a namespace prefix) await bulkUpdateSuccess([obj1, obj2], { namespace }); expectClientCallArgsAction([obj1, obj2], { method: 'update', getId }); + + jest.clearAllMocks(); + // test again with object namespace string that supersedes the operation's namespace ID + await bulkUpdateSuccess([ + { ...obj1, namespace }, + { ...obj2, namespace }, + ]); + expectClientCallArgsAction([obj1, obj2], { method: 'update', getId }); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { - const getId = (type, id) => `${type}:${id}`; + const getId = (type, id) => `${type}:${id}`; // test that the raw document ID equals this (e.g., does not have a namespace prefix) await bulkUpdateSuccess([obj1, obj2]); expectClientCallArgsAction([obj1, obj2], { method: 'update', getId }); + + jest.clearAllMocks(); + // test again with object namespace string that supersedes the operation's namespace ID + await bulkUpdateSuccess( + [ + { ...obj1, namespace: 'default' }, + { ...obj2, namespace: 'default' }, + ], + { namespace } + ); + expectClientCallArgsAction([obj1, obj2], { method: 'update', getId }); }); - it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { + it(`normalizes options.namespace from 'default' to undefined`, async () => { const getId = (type, id) => `${type}:${id}`; - const objects1 = [{ ...obj1, type: NAMESPACE_AGNOSTIC_TYPE }]; - await bulkUpdateSuccess(objects1, { namespace }); - expectClientCallArgsAction(objects1, { method: 'update', getId }); - client.bulk.mockClear(); + await bulkUpdateSuccess([obj1, obj2], { namespace: 'default' }); + expectClientCallArgsAction([obj1, obj2], { method: 'update', getId }); + }); + + it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { + const getId = (type, id) => `${type}:${id}`; // test that the raw document ID equals this (e.g., does not have a namespace prefix) const overrides = { // bulkUpdate uses a preflight `get` request for multi-namespace saved objects, and specifies that version on `update` // we aren't testing for this here, but we need to include Jest assertions so this test doesn't fail if_primary_term: expect.any(Number), if_seq_no: expect.any(Number), }; - const objects2 = [{ ...obj2, type: MULTI_NAMESPACE_TYPE }]; - await bulkUpdateSuccess(objects2, { namespace }); - expectClientCallArgsAction(objects2, { method: 'update', getId, overrides }, 2); + const _obj1 = { ...obj1, type: NAMESPACE_AGNOSTIC_TYPE }; + const _obj2 = { ...obj2, type: MULTI_NAMESPACE_TYPE }; + + await bulkUpdateSuccess([_obj1], { namespace }); + expectClientCallArgsAction([_obj1], { method: 'update', getId }); + client.bulk.mockClear(); + await bulkUpdateSuccess([_obj2], { namespace }); + expectClientCallArgsAction([_obj2], { method: 'update', getId, overrides }, 2); + + jest.clearAllMocks(); + // test again with object namespace string that supersedes the operation's namespace ID + await bulkUpdateSuccess([{ ..._obj1, namespace }]); + expectClientCallArgsAction([_obj1], { method: 'update', getId }); + client.bulk.mockClear(); + await bulkUpdateSuccess([{ ..._obj2, namespace }]); + expectClientCallArgsAction([_obj2], { method: 'update', getId, overrides }, 2); }); }); @@ -1581,19 +1637,25 @@ describe('SavedObjectsRepository', () => { }); it(`prepends namespace to the id when providing namespace for single-namespace type`, async () => { - const getId = (type, id) => `${namespace}:${type}:${id}`; + const getId = (type, id) => `${namespace}:${type}:${id}`; // test that the raw document ID equals this (e.g., has a namespace prefix) await checkConflictsSuccess([obj1, obj2], { namespace }); _expectClientCallArgs([obj1, obj2], { getId }); }); it(`doesn't prepend namespace to the id when providing no namespace for single-namespace type`, async () => { - const getId = (type, id) => `${type}:${id}`; + const getId = (type, id) => `${type}:${id}`; // test that the raw document ID equals this (e.g., does not have a namespace prefix) await checkConflictsSuccess([obj1, obj2]); _expectClientCallArgs([obj1, obj2], { getId }); }); + it(`normalizes options.namespace from 'default' to undefined`, async () => { + const getId = (type, id) => `${type}:${id}`; // test that the raw document ID equals this (e.g., does not have a namespace prefix) + await checkConflictsSuccess([obj1, obj2], { namespace: 'default' }); + _expectClientCallArgs([obj1, obj2], { getId }); + }); + it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { - const getId = (type, id) => `${type}:${id}`; + const getId = (type, id) => `${type}:${id}`; // test that the raw document ID equals this (e.g., does not have a namespace prefix) // obj3 is multi-namespace, and obj6 is namespace-agnostic await checkConflictsSuccess([obj3, obj6], { namespace }); _expectClientCallArgs([obj3, obj6], { getId }); @@ -1816,6 +1878,16 @@ describe('SavedObjectsRepository', () => { ); }); + it(`normalizes options.namespace from 'default' to undefined`, async () => { + await createSuccess(type, attributes, { id, namespace: 'default' }); + expect(client.create).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${type}:${id}`, + }), + expect.anything() + ); + }); + it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { await createSuccess(NAMESPACE_AGNOSTIC_TYPE, attributes, { id, namespace }); expect(client.create).toHaveBeenCalledWith( @@ -1852,11 +1924,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when there is a conflict with an existing multi-namespace saved object (get)`, async () => { - const response = getMockGetResponse({ - type: MULTI_NAMESPACE_TYPE, - id, - namespace: 'bar-namespace', - }); + const response = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id }, 'bar-namespace'); client.get.mockResolvedValueOnce( elasticsearchClientMock.createSuccessTransportRequestPromise(response) ); @@ -1959,7 +2027,7 @@ describe('SavedObjectsRepository', () => { const deleteSuccess = async (type, id, options) => { if (registry.isMultiNamespace(type)) { - const mockGetResponse = getMockGetResponse({ type, id, namespace: options?.namespace }); + const mockGetResponse = getMockGetResponse({ type, id }, options?.namespace); client.get.mockResolvedValueOnce( elasticsearchClientMock.createSuccessTransportRequestPromise(mockGetResponse) ); @@ -2035,6 +2103,14 @@ describe('SavedObjectsRepository', () => { ); }); + it(`normalizes options.namespace from 'default' to undefined`, async () => { + await deleteSuccess(type, id, { namespace: 'default' }); + expect(client.delete).toHaveBeenCalledWith( + expect.objectContaining({ id: `${type}:${id}` }), + expect.anything() + ); + }); + it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { await deleteSuccess(NAMESPACE_AGNOSTIC_TYPE, id, { namespace }); expect(client.delete).toHaveBeenCalledWith( @@ -2085,7 +2161,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when the type is multi-namespace and the document exists, but not in this namespace`, async () => { - const response = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id, namespace }); + const response = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id }, namespace); client.get.mockResolvedValueOnce( elasticsearchClientMock.createSuccessTransportRequestPromise(response) ); @@ -2660,14 +2736,16 @@ describe('SavedObjectsRepository', () => { const originId = 'some-origin-id'; const getSuccess = async (type, id, options, includeOriginId) => { - const response = getMockGetResponse({ - type, - id, - namespace: options?.namespace, - // "includeOriginId" is not an option for the operation; however, if the existing saved object contains an originId attribute, the - // operation will return it in the result. This flag is just used for test purposes to modify the mock cluster call response. - ...(includeOriginId && { originId }), - }); + const response = getMockGetResponse( + { + type, + id, + // "includeOriginId" is not an option for the operation; however, if the existing saved object contains an originId attribute, the + // operation will return it in the result. This flag is just used for test purposes to modify the mock cluster call response. + ...(includeOriginId && { originId }), + }, + options?.namespace + ); client.get.mockResolvedValueOnce( elasticsearchClientMock.createSuccessTransportRequestPromise(response) ); @@ -2702,6 +2780,16 @@ describe('SavedObjectsRepository', () => { ); }); + it(`normalizes options.namespace from 'default' to undefined`, async () => { + await getSuccess(type, id, { namespace: 'default' }); + expect(client.get).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${type}:${id}`, + }), + expect.anything() + ); + }); + it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { await getSuccess(NAMESPACE_AGNOSTIC_TYPE, id, { namespace }); expect(client.get).toHaveBeenCalledWith( @@ -2756,7 +2844,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when type is multi-namespace and the document exists, but not in this namespace`, async () => { - const response = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id, namespace }); + const response = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id }, namespace); client.get.mockResolvedValueOnce( elasticsearchClientMock.createSuccessTransportRequestPromise(response) ); @@ -2812,7 +2900,7 @@ describe('SavedObjectsRepository', () => { const incrementCounterSuccess = async (type, id, field, options) => { const isMultiNamespace = registry.isMultiNamespace(type); if (isMultiNamespace) { - const response = getMockGetResponse({ type, id, namespace: options?.namespace }); + const response = getMockGetResponse({ type, id }, options?.namespace); client.get.mockResolvedValueOnce( elasticsearchClientMock.createSuccessTransportRequestPromise(response) ); @@ -2883,6 +2971,16 @@ describe('SavedObjectsRepository', () => { ); }); + it(`normalizes options.namespace from 'default' to undefined`, async () => { + await incrementCounterSuccess(type, id, field, { namespace: 'default' }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ + id: `${type}:${id}`, + }), + expect.anything() + ); + }); + it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { await incrementCounterSuccess(NAMESPACE_AGNOSTIC_TYPE, id, field, { namespace }); expect(client.update).toHaveBeenCalledWith( @@ -2949,11 +3047,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when there is a conflict with an existing multi-namespace saved object (get)`, async () => { - const response = getMockGetResponse({ - type: MULTI_NAMESPACE_TYPE, - id, - namespace: 'bar-namespace', - }); + const response = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id }, 'bar-namespace'); client.get.mockResolvedValueOnce( elasticsearchClientMock.createSuccessTransportRequestPromise(response) ); @@ -3246,7 +3340,7 @@ describe('SavedObjectsRepository', () => { expect(client.update).not.toHaveBeenCalled(); }); - it(`throws when type is not namespace-agnostic`, async () => { + it(`throws when type is not multi-namespace`, async () => { const test = async (type) => { const message = `${type} doesn't support multiple namespaces`; await expectBadRequestError(type, id, [namespace1, namespace2], message); @@ -3388,7 +3482,7 @@ describe('SavedObjectsRepository', () => { const updateSuccess = async (type, id, attributes, options, includeOriginId) => { if (registry.isMultiNamespace(type)) { - const mockGetResponse = getMockGetResponse({ type, id, namespace: options?.namespace }); + const mockGetResponse = getMockGetResponse({ type, id }, options?.namespace); client.get.mockResolvedValueOnce( elasticsearchClientMock.createSuccessTransportRequestPromise(mockGetResponse) ); @@ -3519,6 +3613,14 @@ describe('SavedObjectsRepository', () => { ); }); + it(`normalizes options.namespace from 'default' to undefined`, async () => { + await updateSuccess(type, id, attributes, { references, namespace: 'default' }); + expect(client.update).toHaveBeenCalledWith( + expect.objectContaining({ id: expect.stringMatching(`${type}:${id}`) }), + expect.anything() + ); + }); + it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { await updateSuccess(NAMESPACE_AGNOSTIC_TYPE, id, attributes, { namespace }); expect(client.update).toHaveBeenCalledWith( @@ -3589,7 +3691,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when type is multi-namespace and the document exists, but not in this namespace`, async () => { - const response = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id, namespace }); + const response = getMockGetResponse({ type: MULTI_NAMESPACE_TYPE, id }, namespace); client.get.mockResolvedValueOnce( elasticsearchClientMock.createSuccessTransportRequestPromise(response) ); diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index e3fb7d2306469..125f97e7feb11 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -67,6 +67,7 @@ import { } from '../../types'; import { SavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import { validateConvertFilterToKueryNode } from './filter_utils'; +import { SavedObjectsUtils } from './utils'; // BEWARE: The SavedObjectClient depends on the implementation details of the SavedObjectsRepository // so any breaking changes to this repository are considered breaking changes to the SavedObjectsClient. @@ -220,13 +221,13 @@ export class SavedObjectsRepository { const { id, migrationVersion, - namespace, overwrite = false, references = [], refresh = DEFAULT_REFRESH_SETTING, originId, version, } = options; + const namespace = normalizeNamespace(options.namespace); if (!this._allowedTypes.includes(type)) { throw SavedObjectsErrorHelpers.createUnsupportedTypeError(type); @@ -293,7 +294,8 @@ export class SavedObjectsRepository { objects: Array>, options: SavedObjectsCreateOptions = {} ): Promise> { - const { namespace, overwrite = false, refresh = DEFAULT_REFRESH_SETTING } = options; + const { overwrite = false, refresh = DEFAULT_REFRESH_SETTING } = options; + const namespace = normalizeNamespace(options.namespace); const time = this._getCurrentTime(); let bulkGetRequestIndexCounter = 0; @@ -468,7 +470,7 @@ export class SavedObjectsRepository { return { errors: [] }; } - const { namespace } = options; + const namespace = normalizeNamespace(options.namespace); let bulkGetRequestIndexCounter = 0; const expectedBulkGetResults: Either[] = objects.map((object) => { @@ -551,7 +553,8 @@ export class SavedObjectsRepository { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } - const { namespace, refresh = DEFAULT_REFRESH_SETTING } = options; + const { refresh = DEFAULT_REFRESH_SETTING } = options; + const namespace = normalizeNamespace(options.namespace); const rawId = this._serializer.generateRawId(namespace, type, id); let preflightResult: SavedObjectsRawDoc | undefined; @@ -560,7 +563,7 @@ export class SavedObjectsRepository { preflightResult = await this.preflightCheckIncludesNamespace(type, id, namespace); const existingNamespaces = getSavedObjectNamespaces(undefined, preflightResult); const remainingNamespaces = existingNamespaces?.filter( - (x) => x !== getNamespaceString(namespace) + (x) => x !== SavedObjectsUtils.namespaceIdToString(namespace) ); if (remainingNamespaces?.length) { @@ -658,7 +661,7 @@ export class SavedObjectsRepository { } `, lang: 'painless', - params: { namespace: getNamespaceString(namespace) }, + params: { namespace }, }, conflicts: 'proceed', ...getSearchDsl(this._mappings, this._registry, { @@ -814,7 +817,7 @@ export class SavedObjectsRepository { objects: SavedObjectsBulkGetObject[] = [], options: SavedObjectsBaseOptions = {} ): Promise> { - const { namespace } = options; + const namespace = normalizeNamespace(options.namespace); if (objects.length === 0) { return { saved_objects: [] }; @@ -884,7 +887,9 @@ export class SavedObjectsRepository { const { originId, updated_at: updatedAt } = doc._source; let namespaces = []; if (!this._registry.isNamespaceAgnostic(type)) { - namespaces = doc._source.namespaces ?? [getNamespaceString(doc._source.namespace)]; + namespaces = doc._source.namespaces ?? [ + SavedObjectsUtils.namespaceIdToString(doc._source.namespace), + ]; } return { @@ -920,7 +925,7 @@ export class SavedObjectsRepository { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } - const { namespace } = options; + const namespace = normalizeNamespace(options.namespace); const { body, statusCode } = await this.client.get>( { @@ -941,7 +946,9 @@ export class SavedObjectsRepository { let namespaces: string[] = []; if (!this._registry.isNamespaceAgnostic(type)) { - namespaces = body._source.namespaces ?? [getNamespaceString(body._source.namespace)]; + namespaces = body._source.namespaces ?? [ + SavedObjectsUtils.namespaceIdToString(body._source.namespace), + ]; } return { @@ -978,7 +985,8 @@ export class SavedObjectsRepository { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } - const { version, namespace, references, refresh = DEFAULT_REFRESH_SETTING } = options; + const { version, references, refresh = DEFAULT_REFRESH_SETTING } = options; + const namespace = normalizeNamespace(options.namespace); let preflightResult: SavedObjectsRawDoc | undefined; if (this._registry.isMultiNamespace(type)) { @@ -1016,7 +1024,9 @@ export class SavedObjectsRepository { const { originId } = body.get._source; let namespaces = []; if (!this._registry.isNamespaceAgnostic(type)) { - namespaces = body.get._source.namespaces ?? [getNamespaceString(body.get._source.namespace)]; + namespaces = body.get._source.namespaces ?? [ + SavedObjectsUtils.namespaceIdToString(body.get._source.namespace), + ]; } return { @@ -1060,6 +1070,7 @@ export class SavedObjectsRepository { } const { version, namespace, refresh = DEFAULT_REFRESH_SETTING } = options; + // we do not need to normalize the namespace to its ID format, since it will be converted to a namespace string before being used const rawId = this._serializer.generateRawId(undefined, type, id); const preflightResult = await this.preflightCheckIncludesNamespace(type, id, namespace); @@ -1122,6 +1133,7 @@ export class SavedObjectsRepository { } const { namespace, refresh = DEFAULT_REFRESH_SETTING } = options; + // we do not need to normalize the namespace to its ID format, since it will be converted to a namespace string before being used const rawId = this._serializer.generateRawId(undefined, type, id); const preflightResult = await this.preflightCheckIncludesNamespace(type, id, namespace); @@ -1208,7 +1220,7 @@ export class SavedObjectsRepository { options: SavedObjectsBulkUpdateOptions = {} ): Promise> { const time = this._getCurrentTime(); - const { namespace } = options; + const namespace = normalizeNamespace(options.namespace); let bulkGetRequestIndexCounter = 0; const expectedBulkGetResults: Either[] = objects.map((object) => { @@ -1225,7 +1237,9 @@ export class SavedObjectsRepository { }; } - const { attributes, references, version } = object; + const { attributes, references, version, namespace: objectNamespace } = object; + // `objectNamespace` is a namespace string, while `namespace` is a namespace ID. + // The object namespace string, if defined, will supersede the operation's namespace ID. const documentToSave = { [type]: attributes, @@ -1242,16 +1256,24 @@ export class SavedObjectsRepository { id, version, documentToSave, + objectNamespace, ...(requiresNamespacesCheck && { esRequestIndex: bulkGetRequestIndexCounter++ }), }, }; }); + const getNamespaceId = (objectNamespace?: string) => + objectNamespace !== undefined + ? SavedObjectsUtils.namespaceStringToId(objectNamespace) + : namespace; + const getNamespaceString = (objectNamespace?: string) => + objectNamespace ?? SavedObjectsUtils.namespaceIdToString(namespace); + const bulkGetDocs = expectedBulkGetResults .filter(isRight) .filter(({ value }) => value.esRequestIndex !== undefined) - .map(({ value: { type, id } }) => ({ - _id: this._serializer.generateRawId(namespace, type, id), + .map(({ value: { type, id, objectNamespace } }) => ({ + _id: this._serializer.generateRawId(getNamespaceId(objectNamespace), type, id), _index: this.getIndexForType(type), _source: ['type', 'namespaces'], })); @@ -1276,14 +1298,25 @@ export class SavedObjectsRepository { return expectedBulkGetResult; } - const { esRequestIndex, id, type, version, documentToSave } = expectedBulkGetResult.value; + const { + esRequestIndex, + id, + type, + version, + documentToSave, + objectNamespace, + } = expectedBulkGetResult.value; + let namespaces; let versionProperties; if (esRequestIndex !== undefined) { const indexFound = bulkGetResponse?.statusCode !== 404; const actualResult = indexFound ? bulkGetResponse?.body.docs[esRequestIndex] : undefined; const docFound = indexFound && actualResult.found === true; - if (!docFound || !this.rawDocExistsInNamespace(actualResult, namespace)) { + if ( + !docFound || + !this.rawDocExistsInNamespace(actualResult, getNamespaceId(objectNamespace)) + ) { return { tag: 'Left' as 'Left', error: { @@ -1294,12 +1327,13 @@ export class SavedObjectsRepository { }; } namespaces = actualResult._source.namespaces ?? [ - getNamespaceString(actualResult._source.namespace), + SavedObjectsUtils.namespaceIdToString(actualResult._source.namespace), ]; versionProperties = getExpectedVersionProperties(version, actualResult); } else { if (this._registry.isSingleNamespace(type)) { - namespaces = [getNamespaceString(namespace)]; + // if `objectNamespace` is undefined, fall back to `options.namespace` + namespaces = [getNamespaceString(objectNamespace)]; } versionProperties = getExpectedVersionProperties(version); } @@ -1315,7 +1349,7 @@ export class SavedObjectsRepository { bulkUpdateParams.push( { update: { - _id: this._serializer.generateRawId(namespace, type, id), + _id: this._serializer.generateRawId(getNamespaceId(objectNamespace), type, id), _index: this.getIndexForType(type), ...versionProperties, }, @@ -1401,7 +1435,8 @@ export class SavedObjectsRepository { throw SavedObjectsErrorHelpers.createUnsupportedTypeError(type); } - const { migrationVersion, namespace, refresh = DEFAULT_REFRESH_SETTING } = options; + const { migrationVersion, refresh = DEFAULT_REFRESH_SETTING } = options; + const namespace = normalizeNamespace(options.namespace); const time = this._getCurrentTime(); let savedObjectNamespace; @@ -1495,7 +1530,7 @@ export class SavedObjectsRepository { const savedObject = this._serializer.rawToSavedObject(raw); const { namespace, type } = savedObject; if (this._registry.isSingleNamespace(type)) { - savedObject.namespaces = [getNamespaceString(namespace)]; + savedObject.namespaces = [SavedObjectsUtils.namespaceIdToString(namespace)]; } return omit(savedObject, 'namespace') as SavedObject; } @@ -1518,7 +1553,7 @@ export class SavedObjectsRepository { } const namespaces = raw._source.namespaces; - return namespaces?.includes(getNamespaceString(namespace)) ?? false; + return namespaces?.includes(SavedObjectsUtils.namespaceIdToString(namespace)) ?? false; } /** @@ -1623,14 +1658,6 @@ function getExpectedVersionProperties(version?: string, document?: SavedObjectsR return {}; } -/** - * Returns the string representation of a namespace. - * The default namespace is undefined, and is represented by the string 'default'. - */ -function getNamespaceString(namespace?: string) { - return namespace ?? 'default'; -} - /** * Returns a string array of namespaces for a given saved object. If the saved object is undefined, the result is an array that contains the * current namespace. Value may be undefined if an existing saved object has no namespaces attribute; this should not happen in normal @@ -1646,9 +1673,16 @@ function getSavedObjectNamespaces( if (document) { return document._source?.namespaces; } - return [getNamespaceString(namespace)]; + return [SavedObjectsUtils.namespaceIdToString(namespace)]; } +/** + * Ensure that a namespace is always in its namespace ID representation. + * This allows `'default'` to be used interchangeably with `undefined`. + */ +const normalizeNamespace = (namespace?: string) => + namespace === undefined ? namespace : SavedObjectsUtils.namespaceStringToId(namespace); + /** * Extracts the contents of a decorated error to return the attributes for bulk operations. */ diff --git a/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts b/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts index ad1a08187dc32..3ff72a86c2f89 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts @@ -21,6 +21,7 @@ import { esKuery, KueryNode } from '../../../../../../plugins/data/server'; import { getRootPropertiesObjects, IndexMapping } from '../../../mappings'; import { ISavedObjectTypeRegistry } from '../../../saved_objects_type_registry'; +import { DEFAULT_NAMESPACE_STRING } from '../utils'; /** * Gets the types based on the type. Uses mappings to support @@ -73,7 +74,7 @@ function getFieldsForTypes( */ function getClauseForType( registry: ISavedObjectTypeRegistry, - namespaces: string[] = ['default'], + namespaces: string[] = [DEFAULT_NAMESPACE_STRING], type: string ) { if (namespaces.length === 0) { @@ -88,11 +89,11 @@ function getClauseForType( }; } else if (registry.isSingleNamespace(type)) { const should: Array> = []; - const eligibleNamespaces = namespaces.filter((namespace) => namespace !== 'default'); + const eligibleNamespaces = namespaces.filter((x) => x !== DEFAULT_NAMESPACE_STRING); if (eligibleNamespaces.length > 0) { should.push({ terms: { namespace: eligibleNamespaces } }); } - if (namespaces.includes('default')) { + if (namespaces.includes(DEFAULT_NAMESPACE_STRING)) { should.push({ bool: { must_not: [{ exists: { field: 'namespace' } }] } }); } if (should.length === 0) { @@ -162,9 +163,7 @@ export function getQueryParams({ // would result in no results being returned, as the wildcard is treated as a literal, and not _actually_ as a wildcard. // We had a good discussion around the tradeoffs here: https://github.com/elastic/kibana/pull/67644#discussion_r441055716 const normalizedNamespaces = namespaces - ? Array.from( - new Set(namespaces.map((namespace) => (namespace === '*' ? 'default' : namespace))) - ) + ? Array.from(new Set(namespaces.map((x) => (x === '*' ? DEFAULT_NAMESPACE_STRING : x)))) : undefined; const bool: any = { diff --git a/src/core/server/saved_objects/service/lib/utils.test.ts b/src/core/server/saved_objects/service/lib/utils.test.ts new file mode 100644 index 0000000000000..ea4fa68242bea --- /dev/null +++ b/src/core/server/saved_objects/service/lib/utils.test.ts @@ -0,0 +1,57 @@ +/* + * 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 { SavedObjectsUtils } from './utils'; + +describe('SavedObjectsUtils', () => { + const { namespaceIdToString, namespaceStringToId } = SavedObjectsUtils; + + describe('#namespaceIdToString', () => { + it('converts `undefined` to default namespace string', () => { + expect(namespaceIdToString(undefined)).toEqual('default'); + }); + + it('leaves other namespace IDs as-is', () => { + expect(namespaceIdToString('foo')).toEqual('foo'); + }); + + it('throws an error when a namespace ID is an empty string', () => { + expect(() => namespaceIdToString('')).toThrowError('namespace cannot be an empty string'); + }); + }); + + describe('#namespaceStringToId', () => { + it('converts default namespace string to `undefined`', () => { + expect(namespaceStringToId('default')).toBeUndefined(); + }); + + it('leaves other namespace strings as-is', () => { + expect(namespaceStringToId('foo')).toEqual('foo'); + }); + + it('throws an error when a namespace string is falsy', () => { + const test = (arg: any) => + expect(() => namespaceStringToId(arg)).toThrowError('namespace must be a non-empty string'); + + test(undefined); + test(null); + test(''); + }); + }); +}); diff --git a/src/core/server/saved_objects/service/lib/utils.ts b/src/core/server/saved_objects/service/lib/utils.ts new file mode 100644 index 0000000000000..6101ad57cc401 --- /dev/null +++ b/src/core/server/saved_objects/service/lib/utils.ts @@ -0,0 +1,53 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export const DEFAULT_NAMESPACE_STRING = 'default'; + +/** + * @public + */ +export class SavedObjectsUtils { + /** + * Converts a given saved object namespace ID to its string representation. All namespace IDs have an identical string representation, with + * the exception of the `undefined` namespace ID (which has a namespace string of `'default'`). + * + * @param namespace The namespace ID, which must be either a non-empty string or `undefined`. + */ + public static namespaceIdToString = (namespace?: string) => { + if (namespace === '') { + throw new TypeError('namespace cannot be an empty string'); + } + + return namespace ?? DEFAULT_NAMESPACE_STRING; + }; + + /** + * Converts a given saved object namespace string to its ID representation. All namespace strings have an identical ID representation, with + * the exception of the `'default'` namespace string (which has a namespace ID of `undefined`). + * + * @param namespace The namespace string, which must be non-empty. + */ + public static namespaceStringToId = (namespace: string) => { + if (!namespace) { + throw new TypeError('namespace must be a non-empty string'); + } + + return namespace !== DEFAULT_NAMESPACE_STRING ? namespace : undefined; + }; +} diff --git a/src/core/server/saved_objects/service/saved_objects_client.ts b/src/core/server/saved_objects/service/saved_objects_client.ts index 347c760f841bc..8c96116de49cb 100644 --- a/src/core/server/saved_objects/service/saved_objects_client.ts +++ b/src/core/server/saved_objects/service/saved_objects_client.ts @@ -80,6 +80,13 @@ export interface SavedObjectsBulkUpdateObject type: string; /** {@inheritdoc SavedObjectAttributes} */ attributes: Partial; + /** + * Optional namespace string to use when searching for this object. If this is defined, it will supersede the namespace ID that is in + * {@link SavedObjectsBulkUpdateOptions}. + * + * Note: the default namespace's string representation is `'default'`, and its ID representation is `undefined`. + **/ + namespace?: string; } /** diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index aef1bda9ccf4e..ec457704e89c7 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -2047,6 +2047,7 @@ export interface SavedObjectsBulkResponse { export interface SavedObjectsBulkUpdateObject extends Pick { attributes: Partial; id: string; + namespace?: string; type: string; } @@ -2630,6 +2631,12 @@ export interface SavedObjectsUpdateResponse extends Omit string; + static namespaceStringToId: (namespace: string) => string | undefined; +} + // @public export class SavedObjectTypeRegistry { getAllTypes(): SavedObjectsType[]; diff --git a/src/dev/build/tasks/os_packages/docker_generator/resources/bin/kibana-docker b/src/dev/build/tasks/os_packages/docker_generator/resources/bin/kibana-docker index d7f137e965327..b02b7cc16ec4a 100755 --- a/src/dev/build/tasks/os_packages/docker_generator/resources/bin/kibana-docker +++ b/src/dev/build/tasks/os_packages/docker_generator/resources/bin/kibana-docker @@ -18,6 +18,8 @@ kibana_vars=( console.enabled console.proxyConfig console.proxyFilter + ops.cGroupOverrides.cpuPath + ops.cGroupOverrides.cpuAcctPath cpu.cgroup.path.override cpuacct.cgroup.path.override csp.rules @@ -279,4 +281,4 @@ umask 0002 # Therefore, we set this value here so that cgroup statistics are # available for the container this process will run in. -exec /usr/share/kibana/bin/kibana --cpu.cgroup.path.override=/ --cpuacct.cgroup.path.override=/ ${longopts} "$@" +exec /usr/share/kibana/bin/kibana --ops.cGroupOverrides.cpuPath=/ --ops.cGroupOverrides.cpuAcctPath=/ ${longopts} "$@" diff --git a/src/legacy/server/config/schema.js b/src/legacy/server/config/schema.js index dd65e45659ffc..ce7a500a00dc8 100644 --- a/src/legacy/server/config/schema.js +++ b/src/legacy/server/config/schema.js @@ -49,22 +49,6 @@ export default () => csp: HANDLED_IN_NEW_PLATFORM, - cpu: Joi.object({ - cgroup: Joi.object({ - path: Joi.object({ - override: Joi.string().default(), - }), - }), - }), - - cpuacct: Joi.object({ - cgroup: Joi.object({ - path: Joi.object({ - override: Joi.string().default(), - }), - }), - }), - server: Joi.object({ name: Joi.string().default(os.hostname()), // keep them for BWC, remove when not used in Legacy. @@ -144,6 +128,10 @@ export default () => ops: Joi.object({ interval: Joi.number().default(5000), + cGroupOverrides: Joi.object().keys({ + cpuPath: Joi.string().default(), + cpuAcctPath: Joi.string().default(), + }), }).default(), plugins: Joi.object({ diff --git a/src/legacy/server/status/lib/metrics.js b/src/legacy/server/status/lib/metrics.js index 2631b245e72ab..478bf0829b1aa 100644 --- a/src/legacy/server/status/lib/metrics.js +++ b/src/legacy/server/status/lib/metrics.js @@ -116,8 +116,8 @@ export class Metrics { async captureCGroups() { try { const cgroup = await cGroupStats({ - cpuPath: this.config.get('cpu.cgroup.path.override'), - cpuAcctPath: this.config.get('cpuacct.cgroup.path.override'), + cpuPath: this.config.get('ops.cGroupOverrides.cpuPath'), + cpuAcctPath: this.config.get('ops.cGroupOverrides.cpuAcctPath'), }); if (isObject(cgroup)) { diff --git a/src/plugins/dashboard/kibana.json b/src/plugins/dashboard/kibana.json index 1b38c6d124fe1..531074f9fa60b 100644 --- a/src/plugins/dashboard/kibana.json +++ b/src/plugins/dashboard/kibana.json @@ -6,6 +6,7 @@ "embeddable", "inspector", "kibanaLegacy", + "urlForwarding", "navigation", "uiActions", "savedObjects" diff --git a/src/plugins/dashboard/public/application/application.ts b/src/plugins/dashboard/public/application/application.ts index 21f423d009ee7..b0a5b0472ec47 100644 --- a/src/plugins/dashboard/public/application/application.ts +++ b/src/plugins/dashboard/public/application/application.ts @@ -41,6 +41,7 @@ import { NavigationPublicPluginStart as NavigationStart } from '../../../navigat import { DataPublicPluginStart } from '../../../data/public'; import { SharePluginStart } from '../../../share/public'; import { KibanaLegacyStart, configureAppAngularModule } from '../../../kibana_legacy/public'; +import { UrlForwardingStart } from '../../../url_forwarding/public'; import { SavedObjectLoader, SavedObjectsStart } from '../../../saved_objects/public'; // required for i18nIdDirective @@ -69,8 +70,8 @@ export interface RenderDeps { localStorage: Storage; share?: SharePluginStart; usageCollection?: UsageCollectionSetup; - navigateToDefaultApp: KibanaLegacyStart['navigateToDefaultApp']; - navigateToLegacyKibanaUrl: KibanaLegacyStart['navigateToLegacyKibanaUrl']; + navigateToDefaultApp: UrlForwardingStart['navigateToDefaultApp']; + navigateToLegacyKibanaUrl: UrlForwardingStart['navigateToLegacyKibanaUrl']; scopedHistory: () => ScopedHistory; savedObjects: SavedObjectsStart; restorePreviousUrl: () => void; diff --git a/src/plugins/dashboard/public/application/dashboard_app_controller.tsx b/src/plugins/dashboard/public/application/dashboard_app_controller.tsx index 212b54be9ae04..92d6f2ed91dde 100644 --- a/src/plugins/dashboard/public/application/dashboard_app_controller.tsx +++ b/src/plugins/dashboard/public/application/dashboard_app_controller.tsx @@ -88,8 +88,8 @@ import { AngularHttpError, KibanaLegacyStart, subscribeWithScope, - migrateLegacyQuery, } from '../../../kibana_legacy/public'; +import { migrateLegacyQuery } from './lib/migrate_legacy_query'; export interface DashboardAppControllerDependencies extends RenderDeps { $scope: DashboardAppScope; diff --git a/src/plugins/dashboard/public/application/dashboard_state_manager.ts b/src/plugins/dashboard/public/application/dashboard_state_manager.ts index 5fed38487dc54..910a2b470b2eb 100644 --- a/src/plugins/dashboard/public/application/dashboard_state_manager.ts +++ b/src/plugins/dashboard/public/application/dashboard_state_manager.ts @@ -25,7 +25,7 @@ import { History } from 'history'; import { Filter, Query, TimefilterContract as Timefilter } from 'src/plugins/data/public'; import { UsageCollectionSetup } from 'src/plugins/usage_collection/public'; -import { migrateLegacyQuery } from '../../../kibana_legacy/public'; +import { migrateLegacyQuery } from './lib/migrate_legacy_query'; import { ViewMode } from '../embeddable_plugin'; import { getAppStateDefaults, migrateAppState, getDashboardIdFromUrl } from './lib'; diff --git a/src/plugins/kibana_legacy/common/migrate_legacy_query.ts b/src/plugins/dashboard/public/application/lib/migrate_legacy_query.ts similarity index 100% rename from src/plugins/kibana_legacy/common/migrate_legacy_query.ts rename to src/plugins/dashboard/public/application/lib/migrate_legacy_query.ts diff --git a/src/plugins/dashboard/public/plugin.tsx b/src/plugins/dashboard/public/plugin.tsx index 0ce6f9489ea02..49584f62215ea 100644 --- a/src/plugins/dashboard/public/plugin.tsx +++ b/src/plugins/dashboard/public/plugin.tsx @@ -33,6 +33,7 @@ import { SavedObjectsClientContract, ScopedHistory, } from 'src/core/public'; +import { UrlForwardingSetup, UrlForwardingStart } from 'src/plugins/url_forwarding/public'; import { UsageCollectionSetup } from '../../usage_collection/public'; import { CONTEXT_MENU_TRIGGER, @@ -125,6 +126,7 @@ interface SetupDependencies { embeddable: EmbeddableSetup; home?: HomePublicPluginSetup; kibanaLegacy: KibanaLegacySetup; + urlForwarding: UrlForwardingSetup; share?: SharePluginSetup; uiActions: UiActionsSetup; usageCollection?: UsageCollectionSetup; @@ -133,6 +135,7 @@ interface SetupDependencies { interface StartDependencies { data: DataPublicPluginStart; kibanaLegacy: KibanaLegacyStart; + urlForwarding: UrlForwardingStart; embeddable: EmbeddableStart; inspector: InspectorStartContract; navigation: NavigationStart; @@ -190,7 +193,16 @@ export class DashboardPlugin public setup( core: CoreSetup, - { share, uiActions, embeddable, home, kibanaLegacy, data, usageCollection }: SetupDependencies + { + share, + uiActions, + embeddable, + home, + kibanaLegacy, + urlForwarding, + data, + usageCollection, + }: SetupDependencies ): Setup { this.dashboardFeatureFlagConfig = this.initializerContext.config.get< DashboardFeatureFlagConfig @@ -311,7 +323,8 @@ export class DashboardPlugin navigation, share: shareStart, data: dataStart, - kibanaLegacy: { dashboardConfig, navigateToDefaultApp, navigateToLegacyKibanaUrl }, + kibanaLegacy: { dashboardConfig }, + urlForwarding: { navigateToDefaultApp, navigateToLegacyKibanaUrl }, savedObjects, } = pluginsStart; @@ -357,7 +370,7 @@ export class DashboardPlugin initAngularBootstrap(); core.application.register(app); - kibanaLegacy.forwardApp( + urlForwarding.forwardApp( DashboardConstants.DASHBOARDS_ID, DashboardConstants.DASHBOARDS_ID, (path) => { @@ -366,7 +379,7 @@ export class DashboardPlugin return `#/list${tail || ''}`; } ); - kibanaLegacy.forwardApp( + urlForwarding.forwardApp( DashboardConstants.DASHBOARD_ID, DashboardConstants.DASHBOARDS_ID, (path) => { diff --git a/src/plugins/data/common/search/aggs/types.ts b/src/plugins/data/common/search/aggs/types.ts index dabd653463d4f..aec3dcc9d068c 100644 --- a/src/plugins/data/common/search/aggs/types.ts +++ b/src/plugins/data/common/search/aggs/types.ts @@ -93,7 +93,7 @@ export interface AggsCommonStart { * is only used internally. The difference is that AggsStart includes the * typings for the registry with initialized agg types. * - * @internal + * @public */ export type AggsStart = Assign; diff --git a/src/plugins/data/kibana.json b/src/plugins/data/kibana.json index b4f20ec6225e2..9cb9b1745373a 100644 --- a/src/plugins/data/kibana.json +++ b/src/plugins/data/kibana.json @@ -13,7 +13,6 @@ "usageCollection", "kibanaUtils", "kibanaReact", - "kibanaLegacy", "inspector" ] } diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index 553ee6bde5f2d..5038af9409316 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -172,7 +172,7 @@ import { } from '../common/field_formats'; import { DateNanosFormat, DateFormat } from './field_formats'; -export { baseFormattersPublic } from './field_formats'; +export { baseFormattersPublic, FieldFormatsStart } from './field_formats'; // Field formats helpers namespace: export const fieldFormats = { @@ -276,6 +276,7 @@ export { QuerySuggestionGetFnArgs, QuerySuggestionBasic, QuerySuggestionField, + AutocompleteStart, } from './autocomplete'; /* @@ -313,6 +314,7 @@ import { export { // aggs + AggConfigSerialized, AggGroupLabels, AggGroupName, AggGroupNames, @@ -337,6 +339,8 @@ export { TabbedTable, } from '../common'; +export type { AggConfigs, AggConfig } from '../common'; + export { // search ES_SEARCH_STRATEGY, @@ -350,6 +354,9 @@ export { IKibanaSearchResponse, injectSearchSourceReferences, ISearch, + ISearchSetup, + ISearchStart, + ISearchStartSearchSource, ISearchGeneric, ISearchSource, parseSearchSourceJSON, @@ -365,6 +372,8 @@ export { EsRawResponseExpressionTypeDefinition, } from './search'; +export type { SearchSource } from './search'; + export { ISearchOptions } from '../common'; // Search namespace @@ -430,8 +439,11 @@ export { TimefilterContract, TimeHistoryContract, QueryStateChange, + QueryStart, } from './query'; +export { AggsStart } from './search/aggs'; + export { getTime, // kbn field types @@ -455,7 +467,13 @@ export function plugin(initializerContext: PluginInitializerContext[]; + // (undocumented) + getField(): any; + // (undocumented) + getFieldDisplayName(): any; + // (undocumented) + getIndexPattern(): import("../../../public").IndexPattern; + // (undocumented) + getKey(bucket: any, key?: string): any; + // (undocumented) + getParam(key: string): any; + // (undocumented) + getRequestAggs(): AggConfig[]; + // (undocumented) + getResponseAggs(): AggConfig[]; + // (undocumented) + getTimeRange(): import("../../../public").TimeRange | undefined; + // (undocumented) + getValue(bucket: any): any; + // (undocumented) + id: string; + // (undocumented) + isFilterable(): boolean; + // (undocumented) + makeLabel(percentageMode?: boolean): any; + static nextId(list: IAggConfig[]): number; + onSearchRequestStart(searchSource: ISearchSource_2, options?: ISearchOptions): Promise | Promise; + // (undocumented) + params: any; + // Warning: (ae-incompatible-release-tags) The symbol "parent" is marked as @public, but its signature references "IAggConfigs" which is marked as @internal + // + // (undocumented) + parent?: IAggConfigs; + // (undocumented) + schema?: string; + // Warning: (ae-incompatible-release-tags) The symbol "serialize" is marked as @public, but its signature references "AggConfigSerialized" which is marked as @internal + // + // (undocumented) + serialize(): AggConfigSerialized; + setParams(from: any): void; + // (undocumented) + setType(type: IAggType): void; + // Warning: (ae-incompatible-release-tags) The symbol "toDsl" is marked as @public, but its signature references "IAggConfigs" which is marked as @internal + toDsl(aggConfigs?: IAggConfigs): any; + // (undocumented) + toExpressionAst(): ExpressionAstFunction | undefined; + // Warning: (ae-incompatible-release-tags) The symbol "toJSON" is marked as @public, but its signature references "AggConfigSerialized" which is marked as @internal + // + // @deprecated (undocumented) + toJSON(): AggConfigSerialized; + // Warning: (ae-forgotten-export) The symbol "SerializableState" needs to be exported by the entry point index.d.ts + toSerializedFieldFormat(): {} | Ensure, SerializableState>; + // (undocumented) + get type(): IAggType; + set type(type: IAggType); + // Warning: (ae-incompatible-release-tags) The symbol "write" is marked as @public, but its signature references "IAggConfigs" which is marked as @internal + // + // (undocumented) + write(aggs?: IAggConfigs): Record; +} + +// Warning: (ae-incompatible-release-tags) The symbol "AggConfigOptions" is marked as @public, but its signature references "AggConfigSerialized" which is marked as @internal // Warning: (ae-missing-release-tag) "AggConfigOptions" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -92,6 +174,76 @@ export type AggConfigOptions = Assign; +// Warning: (ae-missing-release-tag) "AggConfigs" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export class AggConfigs { + // Warning: (ae-forgotten-export) The symbol "AggConfigsOptions" needs to be exported by the entry point index.d.ts + constructor(indexPattern: IndexPattern, configStates: Pick & Pick<{ + type: string | IAggType; + }, "type"> & Pick<{ + type: string | IAggType; + }, never>, "enabled" | "type" | "schema" | "id" | "params">[] | undefined, opts: AggConfigsOptions); + // (undocumented) + aggs: IAggConfig[]; + // (undocumented) + byId(id: string): AggConfig | undefined; + // (undocumented) + byIndex(index: number): AggConfig; + // (undocumented) + byName(name: string): AggConfig[]; + // (undocumented) + bySchemaName(schema: string): AggConfig[]; + // (undocumented) + byType(type: string): AggConfig[]; + // (undocumented) + byTypeName(type: string): AggConfig[]; + // (undocumented) + clone({ enabledOnly }?: { + enabledOnly?: boolean | undefined; + }): AggConfigs; + // Warning: (ae-forgotten-export) The symbol "CreateAggConfigParams" needs to be exported by the entry point index.d.ts + // + // (undocumented) + createAggConfig: (params: CreateAggConfigParams, { addToAggConfigs }?: { + addToAggConfigs?: boolean | undefined; + }) => T; + // (undocumented) + getAll(): AggConfig[]; + // (undocumented) + getRequestAggById(id: string): AggConfig | undefined; + // (undocumented) + getRequestAggs(): AggConfig[]; + getResponseAggById(id: string): AggConfig | undefined; + getResponseAggs(): AggConfig[]; + // (undocumented) + indexPattern: IndexPattern; + jsonDataEquals(aggConfigs: AggConfig[]): boolean; + // (undocumented) + onSearchRequestStart(searchSource: ISearchSource_2, options?: ISearchOptions_2): Promise<[unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown]>; + // (undocumented) + setTimeRange(timeRange: TimeRange): void; + // (undocumented) + timeRange?: TimeRange; + // (undocumented) + toDsl(hierarchical?: boolean): Record; + } + +// @internal (undocumented) +export type AggConfigSerialized = Ensure<{ + type: string; + enabled?: boolean; + id?: string; + params?: {} | SerializableState; + schema?: string; +}, SerializableState>; + // Warning: (ae-missing-release-tag) "AggGroupLabels" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -127,8 +279,6 @@ export type AggParam = BaseParamType; export interface AggParamOption { // (undocumented) display: string; - // Warning: (ae-forgotten-export) The symbol "AggConfig" needs to be exported by the entry point index.d.ts - // // (undocumented) enabled?(agg: AggConfig): boolean; // (undocumented) @@ -142,10 +292,19 @@ export class AggParamType extends Ba constructor(config: Record); // (undocumented) allowedAggs: string[]; + // Warning: (ae-incompatible-release-tags) The symbol "makeAgg" is marked as @public, but its signature references "AggConfigSerialized" which is marked as @internal + // // (undocumented) makeAgg: (agg: TAggConfig, state?: AggConfigSerialized) => TAggConfig; } +// Warning: (ae-forgotten-export) The symbol "AggsCommonStart" needs to be exported by the entry point index.d.ts +// +// @public +export type AggsStart = Assign; + // Warning: (ae-missing-release-tag) "ApplyGlobalFilterActionContext" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -160,6 +319,11 @@ export interface ApplyGlobalFilterActionContext { timeFieldName?: string; } +// Warning: (ae-forgotten-export) The symbol "AutocompleteService" needs to be exported by the entry point index.d.ts +// +// @public (undocumented) +export type AutocompleteStart = ReturnType; + // Warning: (ae-forgotten-export) The symbol "DateFormat" needs to be exported by the entry point index.d.ts // Warning: (ae-forgotten-export) The symbol "DateNanosFormat" needs to be exported by the entry point index.d.ts // Warning: (ae-missing-release-tag) "baseFormattersPublic" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -200,7 +364,6 @@ export enum BUCKET_TYPES { // @public export const castEsToKbnFieldTypeName: (esType: ES_FIELD_TYPES | string) => KBN_FIELD_TYPES; -// Warning: (ae-forgotten-export) The symbol "QueryStart" needs to be exported by the entry point index.d.ts // Warning: (ae-forgotten-export) The symbol "QuerySetup" needs to be exported by the entry point index.d.ts // Warning: (ae-forgotten-export) The symbol "BaseStateContainer" needs to be exported by the entry point index.d.ts // Warning: (ae-missing-release-tag) "connectToQueryState" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -227,7 +390,7 @@ export type CustomFilter = Filter & { // Warning: (ae-missing-release-tag) "DataPublicPluginSetup" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // -// @public (undocumented) +// @public export interface DataPublicPluginSetup { // Warning: (ae-forgotten-export) The symbol "DataPublicPluginEnhancements" needs to be exported by the entry point index.d.ts // @@ -243,42 +406,47 @@ export interface DataPublicPluginSetup { fieldFormats: FieldFormatsSetup; // (undocumented) query: QuerySetup; - // Warning: (ae-forgotten-export) The symbol "ISearchSetup" needs to be exported by the entry point index.d.ts - // // (undocumented) search: ISearchSetup; } // Warning: (ae-missing-release-tag) "DataPublicPluginStart" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // -// @public (undocumented) +// @public export interface DataPublicPluginStart { - // (undocumented) - actions: { - createFiltersFromValueClickAction: typeof createFiltersFromValueClickAction; - createFiltersFromRangeSelectAction: typeof createFiltersFromRangeSelectAction; - }; - // Warning: (ae-forgotten-export) The symbol "AutocompleteStart" needs to be exported by the entry point index.d.ts - // - // (undocumented) + actions: DataPublicPluginStartActions; autocomplete: AutocompleteStart; - // Warning: (ae-forgotten-export) The symbol "FieldFormatsStart" needs to be exported by the entry point index.d.ts - // - // (undocumented) fieldFormats: FieldFormatsStart; - // (undocumented) indexPatterns: IndexPatternsContract; - // (undocumented) query: QueryStart; - // Warning: (ae-forgotten-export) The symbol "ISearchStart" needs to be exported by the entry point index.d.ts + search: ISearchStart; + ui: DataPublicPluginStartUi; +} + +// Warning: (ae-missing-release-tag) "DataPublicPluginStartActions" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public +export interface DataPublicPluginStartActions { + // Warning: (ae-forgotten-export) The symbol "createFiltersFromRangeSelectAction" needs to be exported by the entry point index.d.ts // // (undocumented) - search: ISearchStart; + createFiltersFromRangeSelectAction: typeof createFiltersFromRangeSelectAction; + // Warning: (ae-forgotten-export) The symbol "createFiltersFromValueClickAction" needs to be exported by the entry point index.d.ts + // // (undocumented) - ui: { - IndexPatternSelect: React.ComponentType; - SearchBar: React.ComponentType; - }; + createFiltersFromValueClickAction: typeof createFiltersFromValueClickAction; +} + +// Warning: (ae-missing-release-tag) "DataPublicPluginStartUi" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public +export interface DataPublicPluginStartUi { + // Warning: (ae-forgotten-export) The symbol "IndexPatternSelectProps" needs to be exported by the entry point index.d.ts + // + // (undocumented) + IndexPatternSelect: React.ComponentType; + // (undocumented) + SearchBar: React.ComponentType; } // @public (undocumented) @@ -595,6 +763,11 @@ export type FieldFormatsContentType = 'html' | 'text'; // @public (undocumented) export type FieldFormatsGetConfigFn = GetConfigFn; +// @public (undocumented) +export type FieldFormatsStart = Omit & { + deserialize: FormatFactory; +}; + // Warning: (ae-forgotten-export) The symbol "FieldSpec" needs to be exported by the entry point index.d.ts // Warning: (ae-missing-release-tag) "fieldList" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // @@ -709,8 +882,6 @@ export function getTime(indexPattern: IIndexPattern | undefined, timeRange: Time // @public export type IAggConfig = AggConfig; -// Warning: (ae-forgotten-export) The symbol "AggConfigs" needs to be exported by the entry point index.d.ts -// // @internal export type IAggConfigs = AggConfigs; @@ -1231,11 +1402,40 @@ export interface ISearchOptions { strategy?: string; } -// Warning: (ae-forgotten-export) The symbol "SearchSource" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "ISearchSetup" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // -// @public (undocumented) +// @public +export interface ISearchSetup { + // Warning: (ae-forgotten-export) The symbol "SearchEnhancements" needs to be exported by the entry point index.d.ts + // + // @internal (undocumented) + __enhance: (enhancements: SearchEnhancements) => void; + // Warning: (ae-forgotten-export) The symbol "AggsSetup" needs to be exported by the entry point index.d.ts + // + // (undocumented) + aggs: AggsSetup; + // Warning: (ae-forgotten-export) The symbol "SearchUsageCollector" needs to be exported by the entry point index.d.ts + // + // (undocumented) + usageCollector?: SearchUsageCollector; +} + +// @public export type ISearchSource = Pick; +// @public +export interface ISearchStart { + aggs: AggsStart; + search: ISearchGeneric; + searchSource: ISearchStartSearchSource; +} + +// @public +export interface ISearchStartSearchSource { + create: (fields?: SearchSourceFields) => Promise; + createEmpty: () => ISearchSource; +} + // Warning: (ae-missing-release-tag) "isFilter" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -1450,6 +1650,12 @@ export interface Query { }; } +// Warning: (ae-forgotten-export) The symbol "QueryService" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "QueryStart" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export type QueryStart = ReturnType; + // Warning: (ae-missing-release-tag) "QueryState" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public @@ -1732,11 +1938,6 @@ export class SearchInterceptor { protected application: CoreStart['application']; // (undocumented) protected readonly deps: SearchInterceptorDeps; - getPendingCount$(): Observable; - // @internal (undocumented) - protected hideToast: () => void; - // @internal - protected longRunningToast?: Toast; // @internal protected pendingCount$: BehaviorSubject; // @internal (undocumented) @@ -1750,8 +1951,8 @@ export class SearchInterceptor { combinedSignal: AbortSignal; cleanup: () => void; }; - // @internal (undocumented) - protected showToast: () => void; + // (undocumented) + protected showTimeoutError: ((e: Error) => void) & import("lodash").Cancelable; // @internal protected timeoutSubscriptions: Subscription; } @@ -1768,8 +1969,6 @@ export interface SearchInterceptorDeps { toasts: ToastsSetup; // (undocumented) uiSettings: CoreSetup_2['uiSettings']; - // Warning: (ae-forgotten-export) The symbol "SearchUsageCollector" needs to be exported by the entry point index.d.ts - // // (undocumented) usageCollector?: SearchUsageCollector; } @@ -1777,9 +1976,59 @@ export interface SearchInterceptorDeps { // @internal export type SearchRequest = Record; +// @public (undocumented) +export class SearchSource { + // Warning: (ae-forgotten-export) The symbol "SearchSourceDependencies" needs to be exported by the entry point index.d.ts + constructor(fields: SearchSourceFields | undefined, dependencies: SearchSourceDependencies); + // @deprecated (undocumented) + create(): SearchSource; + createChild(options?: {}): SearchSource; + createCopy(): SearchSource; + destroy(): void; + fetch(options?: ISearchOptions): Promise>; + getField(field: K, recurse?: boolean): SearchSourceFields[K]; + getFields(): { + type?: string | undefined; + query?: import("../..").Query | undefined; + filter?: Filter | Filter[] | (() => Filter | Filter[] | undefined) | undefined; + sort?: Record | Record[] | undefined; + highlight?: any; + highlightAll?: boolean | undefined; + aggs?: any; + from?: number | undefined; + size?: number | undefined; + source?: string | boolean | string[] | undefined; + version?: boolean | undefined; + fields?: string | boolean | string[] | undefined; + index?: import("../..").IndexPattern | undefined; + searchAfter?: import("./types").EsQuerySearchAfter | undefined; + timeout?: string | undefined; + terminate_after?: number | undefined; + }; + getId(): string; + getOwnField(field: K): SearchSourceFields[K]; + getParent(): SearchSource | undefined; + getSearchRequestBody(): Promise; + getSerializedFields(): SearchSourceFields; + // Warning: (ae-incompatible-release-tags) The symbol "history" is marked as @public, but its signature references "SearchRequest" which is marked as @internal + // + // (undocumented) + history: SearchRequest[]; + onRequestStart(handler: (searchSource: SearchSource, options?: ISearchOptions) => Promise): void; + serialize(): { + searchSourceJSON: string; + references: import("../../../../../core/public").SavedObjectReference[]; + }; + setField(field: K, value: SearchSourceFields[K]): this; + setFields(newFields: SearchSourceFields): this; + // Warning: (ae-forgotten-export) The symbol "SearchSourceOptions" needs to be exported by the entry point index.d.ts + setParent(parent?: ISearchSource, options?: SearchSourceOptions): this; + setPreferredSearchStrategyId(searchStrategyId: string): void; +} + // Warning: (ae-missing-release-tag) "SearchSourceFields" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // -// @public (undocumented) +// @public export interface SearchSourceFields { // (undocumented) aggs?: any; @@ -1793,6 +2042,8 @@ export interface SearchSourceFields { highlight?: any; // (undocumented) highlightAll?: boolean; + // Warning: (ae-unresolved-link) The @link reference could not be resolved: The package "kibana" does not have an export "IndexPatternService" + // // (undocumented) index?: IndexPattern; // (undocumented) @@ -1944,6 +2195,8 @@ export const UI_SETTINGS: { // src/plugins/data/common/es_query/filters/match_all_filter.ts:28:3 - (ae-forgotten-export) The symbol "MatchAllFilterMeta" needs to be exported by the entry point index.d.ts // src/plugins/data/common/es_query/filters/phrase_filter.ts:33:3 - (ae-forgotten-export) The symbol "PhraseFilterMeta" needs to be exported by the entry point index.d.ts // src/plugins/data/common/es_query/filters/phrases_filter.ts:31:3 - (ae-forgotten-export) The symbol "PhrasesFilterMeta" needs to be exported by the entry point index.d.ts +// src/plugins/data/common/search/aggs/types.ts:98:51 - (ae-forgotten-export) The symbol "AggTypesRegistryStart" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/field_formats/field_formats_service.ts:67:3 - (ae-forgotten-export) The symbol "FormatFactory" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:66:23 - (ae-forgotten-export) The symbol "FilterLabel" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:66:23 - (ae-forgotten-export) The symbol "FILTERS" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:66:23 - (ae-forgotten-export) The symbol "getDisplayValueFromFilter" needs to be exported by the entry point index.d.ts @@ -1976,25 +2229,22 @@ export const UI_SETTINGS: { // src/plugins/data/public/index.ts:234:27 - (ae-forgotten-export) The symbol "getFromSavedObject" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:234:27 - (ae-forgotten-export) The symbol "flattenHitWrapper" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:234:27 - (ae-forgotten-export) The symbol "formatHitProvider" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:371:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:371:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:371:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:371:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:373:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:374:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:383:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:384:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:385:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:386:1 - (ae-forgotten-export) The symbol "isDateHistogramBucketAggConfig" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:390:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:391:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:394:1 - (ae-forgotten-export) The symbol "parseInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:395:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:398:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:380:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:380:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:380:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:380:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:382:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:383:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:392:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:393:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:394:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:395:1 - (ae-forgotten-export) The symbol "isDateHistogramBucketAggConfig" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:399:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:400:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:403:1 - (ae-forgotten-export) The symbol "parseInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:404:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:407:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts // src/plugins/data/public/query/state_sync/connect_to_query_state.ts:45:5 - (ae-forgotten-export) The symbol "FilterStateStore" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/types.ts:62:5 - (ae-forgotten-export) The symbol "createFiltersFromValueClickAction" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/types.ts:63:5 - (ae-forgotten-export) The symbol "createFiltersFromRangeSelectAction" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/types.ts:71:5 - (ae-forgotten-export) The symbol "IndexPatternSelectProps" needs to be exported by the entry point index.d.ts // (No @packageDocumentation comment for this package) diff --git a/src/plugins/data/public/search/README.md b/src/plugins/data/public/search/README.md index 33e6d9ab0bd1a..0a123ffa3f1e9 100644 --- a/src/plugins/data/public/search/README.md +++ b/src/plugins/data/public/search/README.md @@ -1,13 +1,23 @@ # search -The `search` plugin provides the ability to register search strategies that take in a request -object, and return a response object, of a given shape. +The `search` service provides you with APIs to query Elasticsearch. -Both client side search strategies can be registered, as well as server side search strategies. +The services are split into two parts: (1) low-level API; and (2) high-level API. -The `search` plugin includes two one concrete client side implementations - - `SYNC_SEARCH_STRATEGY` and `ES_SEARCH_STRATEGY` which uses `SYNC_SEARCH_STRATEGY`. There is also one - default server side search strategy, `ES_SEARCH_STRATEGY`. +## Low-level API - Includes the `esSearch` plugin in order to search for data from Elasticsearch using Elasticsearch -DSL. +With low level API you work directly with elasticsearch DSL + +```typescript +const results = await data.search.search(request, params); +``` + +## High-level API + +Using high-level API you work with Kibana abstractions around Elasticsearch DSL: filters, queries, and aggregations. Provided by the *Search Source* service. + +```typescript +const search = data.search.searchSource.createEmpty(); +search.setField('query', data.query.queryString); +const results = await search.fetch(); +``` diff --git a/src/plugins/data/public/search/collectors/create_usage_collector.test.ts b/src/plugins/data/public/search/collectors/create_usage_collector.test.ts index 315d4678cabf1..9cadb1e796ad6 100644 --- a/src/plugins/data/public/search/collectors/create_usage_collector.test.ts +++ b/src/plugins/data/public/search/collectors/create_usage_collector.test.ts @@ -63,31 +63,4 @@ describe('Search Usage Collector', () => { SEARCH_EVENT_TYPE.QUERIES_CANCELLED ); }); - - test('tracks long popups', async () => { - await usageCollector.trackLongQueryPopupShown(); - expect(mockUsageCollectionSetup.reportUiStats).toHaveBeenCalled(); - expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][1]).toBe(METRIC_TYPE.LOADED); - expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][2]).toBe( - SEARCH_EVENT_TYPE.LONG_QUERY_POPUP_SHOWN - ); - }); - - test('tracks long popups dismissed', async () => { - await usageCollector.trackLongQueryDialogDismissed(); - expect(mockUsageCollectionSetup.reportUiStats).toHaveBeenCalled(); - expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][1]).toBe(METRIC_TYPE.CLICK); - expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][2]).toBe( - SEARCH_EVENT_TYPE.LONG_QUERY_DIALOG_DISMISSED - ); - }); - - test('tracks run query beyond timeout', async () => { - await usageCollector.trackLongQueryRunBeyondTimeout(); - expect(mockUsageCollectionSetup.reportUiStats).toHaveBeenCalled(); - expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][1]).toBe(METRIC_TYPE.CLICK); - expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][2]).toBe( - SEARCH_EVENT_TYPE.LONG_QUERY_RUN_BEYOND_TIMEOUT - ); - }); }); diff --git a/src/plugins/data/public/search/collectors/create_usage_collector.ts b/src/plugins/data/public/search/collectors/create_usage_collector.ts index 321b2c5b99049..187ed90652bb2 100644 --- a/src/plugins/data/public/search/collectors/create_usage_collector.ts +++ b/src/plugins/data/public/search/collectors/create_usage_collector.ts @@ -48,29 +48,5 @@ export const createUsageCollector = ( SEARCH_EVENT_TYPE.QUERIES_CANCELLED ); }, - trackLongQueryPopupShown: async () => { - const currentApp = await getCurrentApp(); - return usageCollection?.reportUiStats( - currentApp!, - METRIC_TYPE.LOADED, - SEARCH_EVENT_TYPE.LONG_QUERY_POPUP_SHOWN - ); - }, - trackLongQueryDialogDismissed: async () => { - const currentApp = await getCurrentApp(); - return usageCollection?.reportUiStats( - currentApp!, - METRIC_TYPE.CLICK, - SEARCH_EVENT_TYPE.LONG_QUERY_DIALOG_DISMISSED - ); - }, - trackLongQueryRunBeyondTimeout: async () => { - const currentApp = await getCurrentApp(); - return usageCollection?.reportUiStats( - currentApp!, - METRIC_TYPE.CLICK, - SEARCH_EVENT_TYPE.LONG_QUERY_RUN_BEYOND_TIMEOUT - ); - }, }; }; diff --git a/src/plugins/data/public/search/collectors/types.ts b/src/plugins/data/public/search/collectors/types.ts index 3e98f901eb0c3..bb7fa1e6ae4a2 100644 --- a/src/plugins/data/public/search/collectors/types.ts +++ b/src/plugins/data/public/search/collectors/types.ts @@ -20,15 +20,9 @@ export enum SEARCH_EVENT_TYPE { QUERY_TIMED_OUT = 'queryTimedOut', QUERIES_CANCELLED = 'queriesCancelled', - LONG_QUERY_POPUP_SHOWN = 'longQueryPopupShown', - LONG_QUERY_DIALOG_DISMISSED = 'longQueryDialogDismissed', - LONG_QUERY_RUN_BEYOND_TIMEOUT = 'longQueryRunBeyondTimeout', } export interface SearchUsageCollector { trackQueryTimedOut: () => Promise; trackQueriesCancelled: () => Promise; - trackLongQueryPopupShown: () => Promise; - trackLongQueryDialogDismissed: () => Promise; - trackLongQueryRunBeyondTimeout: () => Promise; } diff --git a/src/plugins/data/public/search/index.ts b/src/plugins/data/public/search/index.ts index a6a1736ac91da..c1af9699acbb2 100644 --- a/src/plugins/data/public/search/index.ts +++ b/src/plugins/data/public/search/index.ts @@ -19,7 +19,14 @@ export * from './expressions'; -export { ISearch, ISearchGeneric, ISearchSetup, ISearchStart, SearchEnhancements } from './types'; +export { + ISearch, + ISearchGeneric, + ISearchSetup, + ISearchStart, + ISearchStartSearchSource, + SearchEnhancements, +} from './types'; export { IEsSearchResponse, IEsSearchRequest, ES_SEARCH_STRATEGY } from '../../common/search'; diff --git a/src/plugins/data/public/search/long_query_notification.tsx b/src/plugins/data/public/search/long_query_notification.tsx deleted file mode 100644 index 1db298618fae8..0000000000000 --- a/src/plugins/data/public/search/long_query_notification.tsx +++ /dev/null @@ -1,59 +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 { EuiButton, EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; -import React from 'react'; -import { ApplicationStart } from 'kibana/public'; -import { toMountPoint } from '../../../kibana_react/public'; - -interface Props { - application: ApplicationStart; -} - -export function getLongQueryNotification(props: Props) { - return toMountPoint(); -} - -export function LongQueryNotification(props: Props) { - return ( -
- - - - - { - await props.application.navigateToApp('management/stack/license_management'); - }} - > - - - - -
- ); -} diff --git a/src/plugins/data/public/search/search_interceptor.test.ts b/src/plugins/data/public/search/search_interceptor.test.ts index 84db69a83a005..7bfa6f0ab1bc5 100644 --- a/src/plugins/data/public/search/search_interceptor.test.ts +++ b/src/plugins/data/public/search/search_interceptor.test.ts @@ -95,6 +95,39 @@ describe('SearchInterceptor', () => { await flushPromises(); }); + test('Should not timeout if requestTimeout is undefined', async () => { + searchInterceptor = new SearchInterceptor({ + startServices: mockCoreSetup.getStartServices(), + uiSettings: mockCoreSetup.uiSettings, + http: mockCoreSetup.http, + toasts: mockCoreSetup.notifications.toasts, + }); + mockCoreSetup.http.fetch.mockImplementationOnce((options: any) => { + return new Promise((resolve, reject) => { + options.signal.addEventListener('abort', () => { + reject(new AbortError()); + }); + + setTimeout(resolve, 5000); + }); + }); + const mockRequest: IEsSearchRequest = { + params: {}, + }; + const response = searchInterceptor.search(mockRequest); + + expect.assertions(1); + const next = jest.fn(); + const complete = () => { + expect(next).toBeCalled(); + }; + response.subscribe({ next, complete }); + + jest.advanceTimersByTime(5000); + + await flushPromises(); + }); + test('Observable should fail if user aborts (test merged signal)', async () => { const abortController = new AbortController(); mockCoreSetup.http.fetch.mockImplementationOnce((options: any) => { @@ -125,7 +158,7 @@ describe('SearchInterceptor', () => { await flushPromises(); }); - test('Immediatelly aborts if passed an aborted abort signal', async (done) => { + test('Immediately aborts if passed an aborted abort signal', async (done) => { const abort = new AbortController(); const mockRequest: IEsSearchRequest = { params: {}, @@ -141,44 +174,4 @@ describe('SearchInterceptor', () => { response.subscribe({ error }); }); }); - - describe('getPendingCount$', () => { - test('should observe the number of pending requests', () => { - const pendingCount$ = searchInterceptor.getPendingCount$(); - const pendingNext = jest.fn(); - pendingCount$.subscribe(pendingNext); - - const mockResponse: any = { result: 200 }; - mockCoreSetup.http.fetch.mockResolvedValue(mockResponse); - const mockRequest: IEsSearchRequest = { - params: {}, - }; - const response = searchInterceptor.search(mockRequest); - - response.subscribe({ - complete: () => { - expect(pendingNext.mock.calls).toEqual([[0], [1], [0]]); - }, - }); - }); - - test('should observe the number of pending requests on error', () => { - const pendingCount$ = searchInterceptor.getPendingCount$(); - const pendingNext = jest.fn(); - pendingCount$.subscribe(pendingNext); - - const mockResponse: any = { result: 500 }; - mockCoreSetup.http.fetch.mockRejectedValue(mockResponse); - const mockRequest: IEsSearchRequest = { - params: {}, - }; - const response = searchInterceptor.search(mockRequest); - - response.subscribe({ - complete: () => { - expect(pendingNext.mock.calls).toEqual([[0], [1], [0]]); - }, - }); - }); - }); }); diff --git a/src/plugins/data/public/search/search_interceptor.ts b/src/plugins/data/public/search/search_interceptor.ts index 0a6d60afed2f7..888e12a4285b1 100644 --- a/src/plugins/data/public/search/search_interceptor.ts +++ b/src/plugins/data/public/search/search_interceptor.ts @@ -17,7 +17,7 @@ * under the License. */ -import { trimEnd } from 'lodash'; +import { trimEnd, debounce } from 'lodash'; import { BehaviorSubject, throwError, @@ -28,25 +28,24 @@ import { Observable, NEVER, } from 'rxjs'; -import { finalize, filter } from 'rxjs/operators'; -import { Toast, CoreStart, ToastsSetup, CoreSetup } from 'kibana/public'; -import { getCombinedSignal, AbortError } from '../../common/utils'; +import { catchError, finalize } from 'rxjs/operators'; +import { CoreStart, CoreSetup, ToastsSetup } from 'kibana/public'; +import { i18n } from '@kbn/i18n'; import { + getCombinedSignal, + AbortError, IEsSearchRequest, IEsSearchResponse, ISearchOptions, ES_SEARCH_STRATEGY, -} from '../../common/search'; -import { getLongQueryNotification } from './long_query_notification'; +} from '../../common'; import { SearchUsageCollector } from './collectors'; -const LONG_QUERY_NOTIFICATION_DELAY = 10000; - export interface SearchInterceptorDeps { - toasts: ToastsSetup; http: CoreSetup['http']; uiSettings: CoreSetup['uiSettings']; startServices: Promise<[CoreStart, any, unknown]>; + toasts: ToastsSetup; usageCollector?: SearchUsageCollector; } @@ -69,12 +68,6 @@ export class SearchInterceptor { */ protected timeoutSubscriptions: Subscription = new Subscription(); - /** - * The current long-running toast (if there is one). - * @internal - */ - protected longRunningToast?: Toast; - /** * @internal */ @@ -89,19 +82,6 @@ export class SearchInterceptor { this.deps.startServices.then(([coreStart]) => { this.application = coreStart.application; }); - - // When search requests go out, a notification is scheduled allowing users to continue the - // request past the timeout. When all search requests complete, we remove the notification. - this.getPendingCount$() - .pipe(filter((count) => count === 0)) - .subscribe(this.hideToast); - } - /** - * Returns an `Observable` over the current number of pending searches. This could mean that one - * of the search requests is still in flight, or that it has only received partial responses. - */ - public getPendingCount$() { - return this.pendingCount$.asObservable(); } /** @@ -146,6 +126,12 @@ export class SearchInterceptor { this.pendingCount$.next(this.pendingCount$.getValue() + 1); return this.runSearch(request, combinedSignal, options?.strategy).pipe( + catchError((e: any) => { + if (e.body?.attributes?.error === 'Request timed out') { + this.showTimeoutError(e); + } + return throwError(e); + }), finalize(() => { this.pendingCount$.next(this.pendingCount$.getValue() - 1); cleanup(); @@ -170,12 +156,10 @@ export class SearchInterceptor { const timeout$ = timeout ? timer(timeout) : NEVER; const subscription = timeout$.subscribe(() => { timeoutController.abort(); + this.showTimeoutError(new AbortError()); }); this.timeoutSubscriptions.add(subscription); - // Schedule the notification to allow users to cancel or wait beyond the timeout - const notificationSubscription = timer(LONG_QUERY_NOTIFICATION_DELAY).subscribe(this.showToast); - // Get a combined `AbortSignal` that will be aborted whenever the first of the following occurs: // 1. The user manually aborts (via `cancelPending`) // 2. The request times out @@ -189,7 +173,6 @@ export class SearchInterceptor { const combinedSignal = getCombinedSignal(signals); const cleanup = () => { this.timeoutSubscriptions.remove(subscription); - notificationSubscription.unsubscribe(); }; combinedSignal.addEventListener('abort', cleanup); @@ -200,36 +183,23 @@ export class SearchInterceptor { }; } - /** - * @internal - */ - protected showToast = () => { - if (this.longRunningToast) return; - this.longRunningToast = this.deps.toasts.addInfo( - { - title: 'Your query is taking a while', - text: getLongQueryNotification({ - application: this.application, + // Right now we are debouncing but we will hook this up with background sessions to show only one + // error notification per session. + protected showTimeoutError = debounce( + (e: Error) => { + this.deps.toasts.addError(e, { + title: 'Timed out', + toastMessage: i18n.translate('data.search.upgradeLicense', { + defaultMessage: + 'One or more queries timed out. With our free Basic tier, your queries never time out.', }), - }, - { - toastLifeTimeMs: 1000000, - } - ); - }; - - /** - * @internal - */ - protected hideToast = () => { - if (this.longRunningToast) { - this.deps.toasts.remove(this.longRunningToast); - delete this.longRunningToast; - if (this.deps.usageCollector) { - this.deps.usageCollector.trackLongQueryDialogDismissed(); - } + }); + }, + 60000, + { + leading: true, } - }; + ); } export type ISearchInterceptor = PublicMethodsOf; diff --git a/src/plugins/data/public/search/search_service.ts b/src/plugins/data/public/search/search_service.ts index f8f4acbe43dfd..6b73761c5a437 100644 --- a/src/plugins/data/public/search/search_service.ts +++ b/src/plugins/data/public/search/search_service.ts @@ -103,7 +103,13 @@ export class SearchService implements Plugin { aggs: this.aggsService.start({ fieldFormats, uiSettings }), search, searchSource: { + /** + * creates searchsource based on serialized search source fields + */ create: createSearchSource(indexPatterns, searchSourceDependencies), + /** + * creates an enpty search source + */ createEmpty: () => { return new SearchSource({}, searchSourceDependencies); }, diff --git a/src/plugins/data/public/search/search_source/create_search_source.ts b/src/plugins/data/public/search/search_source/create_search_source.ts index 4c44f4d62d469..242fbd73fe42b 100644 --- a/src/plugins/data/public/search/search_source/create_search_source.ts +++ b/src/plugins/data/public/search/search_source/create_search_source.ts @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -import { migrateLegacyQuery } from '../../../../kibana_legacy/common'; +import { migrateLegacyQuery } from './migrate_legacy_query'; import { SearchSource, SearchSourceDependencies } from './search_source'; import { IndexPatternsContract } from '../../index_patterns/index_patterns'; import { SearchSourceFields } from './types'; diff --git a/src/plugins/data/public/search/search_source/migrate_legacy_query.ts b/src/plugins/data/public/search/search_source/migrate_legacy_query.ts new file mode 100644 index 0000000000000..8d9b50d5a66b2 --- /dev/null +++ b/src/plugins/data/public/search/search_source/migrate_legacy_query.ts @@ -0,0 +1,37 @@ +/* + * 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 { has } from 'lodash'; +import { Query } from 'src/plugins/data/public'; + +/** + * Creates a standardized query object from old queries that were either strings or pure ES query DSL + * + * @param query - a legacy query, what used to be stored in SearchSource's query property + * @return Object + */ + +export function migrateLegacyQuery(query: Query | { [key: string]: any } | string): Query { + // Lucene was the only option before, so language-less queries are all lucene + if (!has(query, 'language')) { + return { query, language: 'lucene' }; + } + + return query as Query; +} diff --git a/src/plugins/data/public/search/search_source/search_source.ts b/src/plugins/data/public/search/search_source/search_source.ts index 68c7b663b3628..a39898e6a9f52 100644 --- a/src/plugins/data/public/search/search_source/search_source.ts +++ b/src/plugins/data/public/search/search_source/search_source.ts @@ -143,15 +143,19 @@ export class SearchSource { * PUBLIC API *****/ + /** + * internal, dont use + * @param searchStrategyId + */ setPreferredSearchStrategyId(searchStrategyId: string) { this.searchStrategyId = searchStrategyId; } - setFields(newFields: SearchSourceFields) { - this.fields = newFields; - return this; - } - + /** + * sets value to a single search source feild + * @param field: field name + * @param value: value for the field + */ setField(field: K, value: SearchSourceFields[K]) { if (value == null) { delete this.fields[field]; @@ -161,16 +165,33 @@ export class SearchSource { return this; } + /** + * Internal, do not use. Overrides all search source fields with the new field array. + * + * @private + * @param newFields New field array. + */ + setFields(newFields: SearchSourceFields) { + this.fields = newFields; + return this; + } + + /** + * returns search source id + */ getId() { return this.id; } + /** + * returns all search source fields + */ getFields() { return { ...this.fields }; } /** - * Get fields from the fields + * Gets a single field from the fields */ getField(field: K, recurse = true): SearchSourceFields[K] { if (!recurse || this.fields[field] !== void 0) { @@ -187,10 +208,16 @@ export class SearchSource { return this.getField(field, false); } + /** + * @deprecated Don't use. + */ create() { return new SearchSource({}, this.dependencies); } + /** + * creates a copy of this search source (without its children) + */ createCopy() { const newSearchSource = new SearchSource({}, this.dependencies); newSearchSource.setFields({ ...this.fields }); @@ -201,6 +228,10 @@ export class SearchSource { return newSearchSource; } + /** + * creates a new child search source + * @param options + */ createChild(options = {}) { const childSearchSource = new SearchSource({}, this.dependencies); childSearchSource.setParent(this, options); @@ -227,42 +258,6 @@ export class SearchSource { return this.parent; } - /** - * Run a search using the search service - * @return {Observable>} - */ - private fetch$(searchRequest: SearchRequest, options: ISearchOptions) { - const { search, getConfig } = this.dependencies; - - const params = getSearchParamsFromRequest(searchRequest, { - getConfig, - }); - - return search({ params, indexType: searchRequest.indexType }, options).pipe( - map(({ rawResponse }) => handleResponse(searchRequest, rawResponse)) - ); - } - - /** - * Run a search using the search service - * @return {Promise>} - */ - private async legacyFetch(searchRequest: SearchRequest, options: ISearchOptions) { - const { http, getConfig, loadingCount$ } = this.dependencies; - - return await fetchSoon( - searchRequest, - { - ...(this.searchStrategyId && { searchStrategyId: this.searchStrategyId }), - ...options, - }, - { - http, - config: { get: getConfig }, - loadingCount$, - } - ); - } /** * Fetch this source and reject the returned Promise on error * @@ -301,6 +296,9 @@ export class SearchSource { this.requestStartHandlers.push(handler); } + /** + * Returns body contents of the search request, often referred as query DSL. + */ async getSearchRequestBody() { const searchRequest = await this.flatten(); return searchRequest.body; @@ -318,6 +316,43 @@ export class SearchSource { * PRIVATE APIS ******/ + /** + * Run a search using the search service + * @return {Observable>} + */ + private fetch$(searchRequest: SearchRequest, options: ISearchOptions) { + const { search, getConfig } = this.dependencies; + + const params = getSearchParamsFromRequest(searchRequest, { + getConfig, + }); + + return search({ params, indexType: searchRequest.indexType }, options).pipe( + map(({ rawResponse }) => handleResponse(searchRequest, rawResponse)) + ); + } + + /** + * Run a search using the search service + * @return {Promise>} + */ + private async legacyFetch(searchRequest: SearchRequest, options: ISearchOptions) { + const { http, getConfig, loadingCount$ } = this.dependencies; + + return await fetchSoon( + searchRequest, + { + ...(this.searchStrategyId && { searchStrategyId: this.searchStrategyId }), + ...options, + }, + { + http, + config: { get: getConfig }, + loadingCount$, + } + ); + } + /** * Called by requests of this search source when they are started * @param options @@ -480,6 +515,9 @@ export class SearchSource { return searchRequest; } + /** + * serializes search source fields (which can later be passed to {@link ISearchStartSearchSource}) + */ public getSerializedFields() { const { filter: originalFilters, ...searchSourceFields } = omit(this.getFields(), [ 'sort', @@ -531,5 +569,8 @@ export class SearchSource { } } -/** @public **/ +/** + * search source interface + * @public + */ export type ISearchSource = Pick; diff --git a/src/plugins/data/public/search/search_source/types.ts b/src/plugins/data/public/search/search_source/types.ts index c2f8701a64fa3..0882aa9a2ceec 100644 --- a/src/plugins/data/public/search/search_source/types.ts +++ b/src/plugins/data/public/search/search_source/types.ts @@ -34,19 +34,37 @@ export interface SortDirectionNumeric { export type EsQuerySortValue = Record; +/** + * search source fields + */ export interface SearchSourceFields { type?: string; + /** + * {@link Query} + */ query?: Query; + /** + * {@link Filter} + */ filter?: Filter[] | Filter | (() => Filter[] | Filter | undefined); + /** + * {@link EsQuerySortValue} + */ sort?: EsQuerySortValue | EsQuerySortValue[]; highlight?: any; highlightAll?: boolean; + /** + * {@link AggConfigs} + */ aggs?: any; from?: number; size?: number; source?: NameList; version?: boolean; fields?: NameList; + /** + * {@link IndexPatternService} + */ index?: IndexPattern; searchAfter?: EsQuerySearchAfter; timeout?: string; diff --git a/src/plugins/data/public/search/types.ts b/src/plugins/data/public/search/types.ts index cec5c63294e96..83a542269046f 100644 --- a/src/plugins/data/public/search/types.ts +++ b/src/plugins/data/public/search/types.ts @@ -62,13 +62,42 @@ export interface ISearchSetup { __enhance: (enhancements: SearchEnhancements) => void; } +/** + * high level search service + * @public + */ +export interface ISearchStartSearchSource { + /** + * creates {@link SearchSource} based on provided serialized {@link SearchSourceFields} + * @param fields + */ + create: (fields?: SearchSourceFields) => Promise; + /** + * creates empty {@link SearchSource} + */ + createEmpty: () => ISearchSource; +} +/** + * search service + * @public + */ export interface ISearchStart { + /** + * agg config sub service + * {@link AggsStart} + * + */ aggs: AggsStart; + /** + * low level search + * {@link ISearchGeneric} + */ search: ISearchGeneric; - searchSource: { - create: (fields?: SearchSourceFields) => Promise; - createEmpty: () => ISearchSource; - }; + /** + * high level search + * {@link ISearchStartSearchSource} + */ + searchSource: ISearchStartSearchSource; } export { SEARCH_EVENT_TYPE } from './collectors'; diff --git a/src/plugins/data/public/types.ts b/src/plugins/data/public/types.ts index bffc10642eb47..7b5d79aff24ef 100644 --- a/src/plugins/data/public/types.ts +++ b/src/plugins/data/public/types.ts @@ -46,6 +46,9 @@ export interface DataStartDependencies { uiActions: UiActionsStart; } +/** + * Data plugin public Setup contract + */ export interface DataPublicPluginSetup { autocomplete: AutocompleteSetup; search: ISearchSetup; @@ -57,20 +60,61 @@ export interface DataPublicPluginSetup { __enhance: (enhancements: DataPublicPluginEnhancements) => void; } +/** + * Data plugin prewired UI components + */ +export interface DataPublicPluginStartUi { + IndexPatternSelect: React.ComponentType; + SearchBar: React.ComponentType; +} + +/** + * utilities to generate filters from action context + */ +export interface DataPublicPluginStartActions { + createFiltersFromValueClickAction: typeof createFiltersFromValueClickAction; + createFiltersFromRangeSelectAction: typeof createFiltersFromRangeSelectAction; +} + +/** + * Data plugin public Start contract + */ export interface DataPublicPluginStart { - actions: { - createFiltersFromValueClickAction: typeof createFiltersFromValueClickAction; - createFiltersFromRangeSelectAction: typeof createFiltersFromRangeSelectAction; - }; + /** + * filter creation utilities + * {@link DataPublicPluginStartActions} + */ + actions: DataPublicPluginStartActions; + /** + * autocomplete service + * {@link AutocompleteStart} + */ autocomplete: AutocompleteStart; + /** + * index patterns service + * {@link IndexPatternsContract} + */ indexPatterns: IndexPatternsContract; + /** + * search service + * {@link ISearchStart} + */ search: ISearchStart; + /** + * field formats service + * {@link FieldFormatsStart} + */ fieldFormats: FieldFormatsStart; + /** + * query service + * {@link QueryStart} + */ query: QueryStart; - ui: { - IndexPatternSelect: React.ComponentType; - SearchBar: React.ComponentType; - }; + /** + * prewired UI components + * {@link DataPublicPluginStartUi} + */ + ui: DataPublicPluginStartUi; } export interface IDataPluginServices extends Partial { diff --git a/src/plugins/data/server/search/es_search/es_search_strategy.ts b/src/plugins/data/server/search/es_search/es_search_strategy.ts index 106f974ed3457..e2ed500689cfa 100644 --- a/src/plugins/data/server/search/es_search/es_search_strategy.ts +++ b/src/plugins/data/server/search/es_search/es_search_strategy.ts @@ -52,10 +52,11 @@ export const esSearchStrategyProvider = ( }); try { - const esResponse = (await context.core.elasticsearch.client.asCurrentUser.search( - params - )) as ApiResponse>; - const rawResponse = esResponse.body; + // Temporary workaround until https://github.com/elastic/elasticsearch-js/issues/1297 + const promise = context.core.elasticsearch.client.asCurrentUser.search(params); + if (options?.abortSignal) + options.abortSignal.addEventListener('abort', () => promise.abort()); + const { body: rawResponse } = (await promise) as ApiResponse>; if (usage) usage.trackSuccess(rawResponse.took); diff --git a/src/plugins/data/server/search/types.ts b/src/plugins/data/server/search/types.ts index b2b958454de48..aefdac2ab639f 100644 --- a/src/plugins/data/server/search/types.ts +++ b/src/plugins/data/server/search/types.ts @@ -20,7 +20,7 @@ import { RequestHandlerContext } from '../../../../core/server'; import { ISearchOptions } from '../../common/search'; import { AggsSetup, AggsStart } from './aggs'; -import { SearchUsage } from './collectors/usage'; +import { SearchUsage } from './collectors'; import { IEsSearchRequest, IEsSearchResponse } from './es_search'; export interface SearchEnhancements { diff --git a/src/plugins/dev_tools/kibana.json b/src/plugins/dev_tools/kibana.json index d83cabd0f0817..f1c6c9ecf87e6 100644 --- a/src/plugins/dev_tools/kibana.json +++ b/src/plugins/dev_tools/kibana.json @@ -3,5 +3,5 @@ "version": "kibana", "server": false, "ui": true, - "requiredPlugins": ["kibanaLegacy"] + "requiredPlugins": ["urlForwarding"] } diff --git a/src/plugins/dev_tools/public/plugin.ts b/src/plugins/dev_tools/public/plugin.ts index 45fa3634bc87e..fcc6a57361a94 100644 --- a/src/plugins/dev_tools/public/plugin.ts +++ b/src/plugins/dev_tools/public/plugin.ts @@ -24,7 +24,7 @@ import { i18n } from '@kbn/i18n'; import { sortBy } from 'lodash'; import { AppNavLinkStatus, DEFAULT_APP_CATEGORIES } from '../../../core/public'; -import { KibanaLegacySetup } from '../../kibana_legacy/public'; +import { UrlForwardingSetup } from '../../url_forwarding/public'; import { CreateDevToolArgs, DevToolApp, createDevToolApp } from './dev_tool'; import './index.scss'; @@ -51,7 +51,7 @@ export class DevToolsPlugin implements Plugin { return sortBy([...this.devTools.values()], 'order'); } - public setup(coreSetup: CoreSetup, { kibanaLegacy }: { kibanaLegacy: KibanaLegacySetup }) { + public setup(coreSetup: CoreSetup, { urlForwarding }: { urlForwarding: UrlForwardingSetup }) { const { application: applicationSetup, getStartServices } = coreSetup; applicationSetup.register({ @@ -75,7 +75,7 @@ export class DevToolsPlugin implements Plugin { }, }); - kibanaLegacy.forwardApp('dev_tools', 'dev_tools'); + urlForwarding.forwardApp('dev_tools', 'dev_tools'); return { register: (devToolArgs: CreateDevToolArgs) => { diff --git a/src/plugins/discover/kibana.json b/src/plugins/discover/kibana.json index 041f362bf0623..1a23f6deb5fa5 100644 --- a/src/plugins/discover/kibana.json +++ b/src/plugins/discover/kibana.json @@ -9,6 +9,7 @@ "embeddable", "inspector", "kibanaLegacy", + "urlForwarding", "navigation", "uiActions", "visualizations" diff --git a/src/plugins/discover/public/application/angular/discover_state.ts b/src/plugins/discover/public/application/angular/discover_state.ts index ff8fb9f80a723..ac0dc054485f0 100644 --- a/src/plugins/discover/public/application/angular/discover_state.ts +++ b/src/plugins/discover/public/application/angular/discover_state.ts @@ -28,7 +28,7 @@ import { withNotifyOnErrors, } from '../../../../kibana_utils/public'; import { esFilters, Filter, Query } from '../../../../data/public'; -import { migrateLegacyQuery } from '../../../../kibana_legacy/public'; +import { migrateLegacyQuery } from '../helpers/migrate_legacy_query'; export interface AppState { /** diff --git a/src/plugins/discover/public/application/angular/redirect.ts b/src/plugins/discover/public/application/angular/redirect.ts index bfa2f07f852e9..d3fb47f329d4b 100644 --- a/src/plugins/discover/public/application/angular/redirect.ts +++ b/src/plugins/discover/public/application/angular/redirect.ts @@ -24,10 +24,10 @@ getAngularModule().config(($routeProvider: any) => { const path = window.location.hash.substr(1); getUrlTracker().restorePreviousUrl(); $rootScope.$applyAsync(() => { - const { kibanaLegacy } = getServices(); - const { navigated } = kibanaLegacy.navigateToLegacyKibanaUrl(path); + const { urlForwarding } = getServices(); + const { navigated } = urlForwarding.navigateToLegacyKibanaUrl(path); if (!navigated) { - kibanaLegacy.navigateToDefaultApp(); + urlForwarding.navigateToDefaultApp(); } }); // prevent angular from completing the navigation diff --git a/src/plugins/discover/public/application/helpers/migrate_legacy_query.ts b/src/plugins/discover/public/application/helpers/migrate_legacy_query.ts new file mode 100644 index 0000000000000..8d9b50d5a66b2 --- /dev/null +++ b/src/plugins/discover/public/application/helpers/migrate_legacy_query.ts @@ -0,0 +1,37 @@ +/* + * 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 { has } from 'lodash'; +import { Query } from 'src/plugins/data/public'; + +/** + * Creates a standardized query object from old queries that were either strings or pure ES query DSL + * + * @param query - a legacy query, what used to be stored in SearchSource's query property + * @return Object + */ + +export function migrateLegacyQuery(query: Query | { [key: string]: any } | string): Query { + // Lucene was the only option before, so language-less queries are all lucene + if (!has(query, 'language')) { + return { query, language: 'lucene' }; + } + + return query as Query; +} diff --git a/src/plugins/discover/public/build_services.ts b/src/plugins/discover/public/build_services.ts index 75c83e30d80ad..12562d8571a25 100644 --- a/src/plugins/discover/public/build_services.ts +++ b/src/plugins/discover/public/build_services.ts @@ -43,6 +43,7 @@ import { DiscoverStartPlugins } from './plugin'; import { createSavedSearchesLoader, SavedSearch } from './saved_searches'; import { getHistory } from './kibana_services'; import { KibanaLegacyStart } from '../../kibana_legacy/public'; +import { UrlForwardingStart } from '../../url_forwarding/public'; export interface DiscoverServices { addBasePath: (path: string) => string; @@ -59,6 +60,7 @@ export interface DiscoverServices { metadata: { branch: string }; share?: SharePluginStart; kibanaLegacy: KibanaLegacyStart; + urlForwarding: UrlForwardingStart; timefilter: TimefilterContract; toastNotifications: ToastsStart; getSavedSearchById: (id: string) => Promise; @@ -100,6 +102,7 @@ export async function buildServices( }, share: plugins.share, kibanaLegacy: plugins.kibanaLegacy, + urlForwarding: plugins.urlForwarding, timefilter: plugins.data.query.timefilter.timefilter, toastNotifications: core.notifications.toasts, uiSettings: core.uiSettings, diff --git a/src/plugins/discover/public/plugin.ts b/src/plugins/discover/public/plugin.ts index 015f4267646c1..b6960c8a20abf 100644 --- a/src/plugins/discover/public/plugin.ts +++ b/src/plugins/discover/public/plugin.ts @@ -37,6 +37,7 @@ import { NavigationPublicPluginStart as NavigationStart } from 'src/plugins/navi import { SharePluginStart, SharePluginSetup, UrlGeneratorContract } from 'src/plugins/share/public'; import { VisualizationsStart, VisualizationsSetup } from 'src/plugins/visualizations/public'; import { KibanaLegacySetup, KibanaLegacyStart } from 'src/plugins/kibana_legacy/public'; +import { UrlForwardingSetup, UrlForwardingStart } from 'src/plugins/url_forwarding/public'; import { HomePublicPluginSetup } from 'src/plugins/home/public'; import { Start as InspectorPublicPluginStart } from 'src/plugins/inspector/public'; import { DataPublicPluginStart, DataPublicPluginSetup, esFilters } from '../../data/public'; @@ -119,6 +120,7 @@ export interface DiscoverSetupPlugins { uiActions: UiActionsSetup; embeddable: EmbeddableSetup; kibanaLegacy: KibanaLegacySetup; + urlForwarding: UrlForwardingSetup; home?: HomePublicPluginSetup; visualizations: VisualizationsSetup; data: DataPublicPluginSetup; @@ -135,6 +137,7 @@ export interface DiscoverStartPlugins { data: DataPublicPluginStart; share?: SharePluginStart; kibanaLegacy: KibanaLegacyStart; + urlForwarding: UrlForwardingStart; inspector: InspectorPublicPluginStart; visualizations: VisualizationsStart; } @@ -267,13 +270,13 @@ export class DiscoverPlugin }, }); - plugins.kibanaLegacy.forwardApp('doc', 'discover', (path) => { + plugins.urlForwarding.forwardApp('doc', 'discover', (path) => { return `#${path}`; }); - plugins.kibanaLegacy.forwardApp('context', 'discover', (path) => { + plugins.urlForwarding.forwardApp('context', 'discover', (path) => { return `#${path}`; }); - plugins.kibanaLegacy.forwardApp('discover', 'discover', (path) => { + plugins.urlForwarding.forwardApp('discover', 'discover', (path) => { const [, id, tail] = /discover\/([^\?]+)(.*)/.exec(path) || []; if (!id) { return `#${path.replace('/discover', '') || '/'}`; diff --git a/src/plugins/home/kibana.json b/src/plugins/home/kibana.json index 74bd3625ca964..81bfc57a00363 100644 --- a/src/plugins/home/kibana.json +++ b/src/plugins/home/kibana.json @@ -3,7 +3,7 @@ "version": "kibana", "server": true, "ui": true, - "requiredPlugins": ["data", "kibanaLegacy"], + "requiredPlugins": ["data", "urlForwarding"], "optionalPlugins": ["usageCollection", "telemetry"], "requiredBundles": [ "kibanaReact" diff --git a/src/plugins/home/public/application/components/home_app.js b/src/plugins/home/public/application/components/home_app.js index 90e549c873436..69cd68d553d03 100644 --- a/src/plugins/home/public/application/components/home_app.js +++ b/src/plugins/home/public/application/components/home_app.js @@ -32,8 +32,8 @@ import { useMount } from 'react-use'; const RedirectToDefaultApp = () => { useMount(() => { - const { kibanaLegacy } = getServices(); - kibanaLegacy.navigateToDefaultApp(); + const { urlForwarding } = getServices(); + urlForwarding.navigateToDefaultApp(); }); return null; }; diff --git a/src/plugins/home/public/application/kibana_services.ts b/src/plugins/home/public/application/kibana_services.ts index 8bd651d038128..74b2bf8d4f6a4 100644 --- a/src/plugins/home/public/application/kibana_services.ts +++ b/src/plugins/home/public/application/kibana_services.ts @@ -29,7 +29,7 @@ import { } from 'kibana/public'; import { UiStatsMetricType } from '@kbn/analytics'; import { TelemetryPluginStart } from '../../../telemetry/public'; -import { KibanaLegacyStart } from '../../../kibana_legacy/public'; +import { UrlForwardingStart } from '../../../url_forwarding/public'; import { TutorialService } from '../services/tutorials'; import { FeatureCatalogueRegistry } from '../services/feature_catalogue'; import { EnvironmentService } from '../services/environment'; @@ -41,7 +41,7 @@ export interface HomeKibanaServices { chrome: ChromeStart; application: ApplicationStart; uiSettings: IUiSettingsClient; - kibanaLegacy: KibanaLegacyStart; + urlForwarding: UrlForwardingStart; homeConfig: ConfigSchema; featureCatalogue: FeatureCatalogueRegistry; http: HttpStart; diff --git a/src/plugins/home/public/plugin.test.ts b/src/plugins/home/public/plugin.test.ts index 0ebba06e6bea9..7b56c6ec89b77 100644 --- a/src/plugins/home/public/plugin.test.ts +++ b/src/plugins/home/public/plugin.test.ts @@ -20,7 +20,7 @@ import { registryMock, environmentMock, tutorialMock } from './plugin.test.mocks'; import { HomePublicPlugin } from './plugin'; import { coreMock } from '../../../core/public/mocks'; -import { kibanaLegacyPluginMock } from '../../kibana_legacy/public/mocks'; +import { urlForwardingPluginMock } from '../../url_forwarding/public/mocks'; const mockInitializerContext = coreMock.createPluginInitializerContext(); @@ -37,7 +37,7 @@ describe('HomePublicPlugin', () => { const setup = await new HomePublicPlugin(mockInitializerContext).setup( coreMock.createSetup() as any, { - kibanaLegacy: kibanaLegacyPluginMock.createSetupContract(), + urlForwarding: urlForwardingPluginMock.createSetupContract(), } ); expect(setup).toHaveProperty('featureCatalogue'); @@ -56,7 +56,7 @@ describe('HomePublicPlugin', () => { const setup = await new HomePublicPlugin(mockInitializerContext).setup( coreMock.createSetup() as any, { - kibanaLegacy: kibanaLegacyPluginMock.createSetupContract(), + urlForwarding: urlForwardingPluginMock.createSetupContract(), } ); expect(setup).toHaveProperty('featureCatalogue'); @@ -73,7 +73,7 @@ describe('HomePublicPlugin', () => { const setup = await new HomePublicPlugin(mockInitializerContext).setup( coreMock.createSetup() as any, { - kibanaLegacy: kibanaLegacyPluginMock.createSetupContract(), + urlForwarding: urlForwardingPluginMock.createSetupContract(), } ); expect(setup).toHaveProperty('featureCatalogue'); @@ -84,7 +84,7 @@ describe('HomePublicPlugin', () => { const setup = await new HomePublicPlugin(mockInitializerContext).setup( coreMock.createSetup() as any, { - kibanaLegacy: kibanaLegacyPluginMock.createSetupContract(), + urlForwarding: urlForwardingPluginMock.createSetupContract(), } ); expect(setup).toHaveProperty('environment'); @@ -95,7 +95,7 @@ describe('HomePublicPlugin', () => { const setup = await new HomePublicPlugin(mockInitializerContext).setup( coreMock.createSetup() as any, { - kibanaLegacy: kibanaLegacyPluginMock.createSetupContract(), + urlForwarding: urlForwardingPluginMock.createSetupContract(), } ); expect(setup).toHaveProperty('tutorials'); diff --git a/src/plugins/home/public/plugin.ts b/src/plugins/home/public/plugin.ts index ba2f537e7c5de..b62ceae3d0d37 100644 --- a/src/plugins/home/public/plugin.ts +++ b/src/plugins/home/public/plugin.ts @@ -41,19 +41,19 @@ import { setServices } from './application/kibana_services'; import { DataPublicPluginStart } from '../../data/public'; import { TelemetryPluginStart } from '../../telemetry/public'; import { UsageCollectionSetup } from '../../usage_collection/public'; -import { KibanaLegacySetup, KibanaLegacyStart } from '../../kibana_legacy/public'; +import { UrlForwardingSetup, UrlForwardingStart } from '../../url_forwarding/public'; import { AppNavLinkStatus } from '../../../core/public'; import { PLUGIN_ID, HOME_APP_BASE_PATH } from '../common/constants'; export interface HomePluginStartDependencies { data: DataPublicPluginStart; telemetry?: TelemetryPluginStart; - kibanaLegacy: KibanaLegacyStart; + urlForwarding: UrlForwardingStart; } export interface HomePluginSetupDependencies { usageCollection?: UsageCollectionSetup; - kibanaLegacy: KibanaLegacySetup; + urlForwarding: UrlForwardingSetup; } export class HomePublicPlugin @@ -67,7 +67,7 @@ export class HomePublicPlugin public setup( core: CoreSetup, - { kibanaLegacy, usageCollection }: HomePluginSetupDependencies + { urlForwarding, usageCollection }: HomePluginSetupDependencies ): HomePublicPluginSetup { core.application.register({ id: PLUGIN_ID, @@ -79,7 +79,7 @@ export class HomePublicPlugin : () => {}; const [ coreStart, - { telemetry, data, kibanaLegacy: kibanaLegacyStart }, + { telemetry, data, urlForwarding: urlForwardingStart }, ] = await core.getStartServices(); setServices({ trackUiMetric, @@ -97,7 +97,7 @@ export class HomePublicPlugin getBasePath: core.http.basePath.get, indexPatternService: data.indexPatterns, environmentService: this.environmentService, - kibanaLegacy: kibanaLegacyStart, + urlForwarding: urlForwardingStart, homeConfig: this.initializerContext.config.get(), tutorialService: this.tutorialService, featureCatalogue: this.featuresCatalogueRegistry, @@ -109,7 +109,7 @@ export class HomePublicPlugin return await renderApp(params.element, coreStart, params.history); }, }); - kibanaLegacy.forwardApp('home', 'home'); + urlForwarding.forwardApp('home', 'home'); const featureCatalogue = { ...this.featuresCatalogueRegistry.setup() }; @@ -170,7 +170,7 @@ export class HomePublicPlugin public start( { application: { capabilities, currentAppId$ }, http }: CoreStart, - { kibanaLegacy }: HomePluginStartDependencies + { urlForwarding }: HomePluginStartDependencies ) { this.featuresCatalogueRegistry.start({ capabilities }); @@ -184,7 +184,7 @@ export class HomePublicPlugin if (appId === 'home') { // ...navigate to default app set by `kibana.defaultAppId`. // This doesn't do anything as along as the default settings are kept. - kibanaLegacy.navigateToDefaultApp({ overwriteHash: false }); + urlForwarding.navigateToDefaultApp({ overwriteHash: false }); } }); } diff --git a/src/plugins/index_pattern_management/kibana.json b/src/plugins/index_pattern_management/kibana.json index d0ad6a96065c3..6c3025485bbd7 100644 --- a/src/plugins/index_pattern_management/kibana.json +++ b/src/plugins/index_pattern_management/kibana.json @@ -3,6 +3,6 @@ "version": "kibana", "server": true, "ui": true, - "requiredPlugins": ["management", "data", "kibanaLegacy"], + "requiredPlugins": ["management", "data", "urlForwarding"], "requiredBundles": ["kibanaReact", "kibanaUtils"] } diff --git a/src/plugins/index_pattern_management/public/mocks.ts b/src/plugins/index_pattern_management/public/mocks.ts index 6a9ef23e3732e..24aea961764a9 100644 --- a/src/plugins/index_pattern_management/public/mocks.ts +++ b/src/plugins/index_pattern_management/public/mocks.ts @@ -20,7 +20,7 @@ import { PluginInitializerContext } from 'src/core/public'; import { coreMock } from '../../../core/public/mocks'; import { managementPluginMock } from '../../management/public/mocks'; -import { kibanaLegacyPluginMock } from '../../kibana_legacy/public/mocks'; +import { urlForwardingPluginMock } from '../../url_forwarding/public/mocks'; import { dataPluginMock } from '../../data/public/mocks'; import { IndexPatternManagementSetup, @@ -65,7 +65,7 @@ const createInstance = async () => { const setup = plugin.setup(coreMock.createSetup(), { management: managementPluginMock.createSetupContract(), - kibanaLegacy: kibanaLegacyPluginMock.createSetupContract(), + urlForwarding: urlForwardingPluginMock.createSetupContract(), }); const doStart = () => plugin.start(coreMock.createStart(), { diff --git a/src/plugins/index_pattern_management/public/plugin.ts b/src/plugins/index_pattern_management/public/plugin.ts index ee1e00fcafd98..cfe0a23eb14dd 100644 --- a/src/plugins/index_pattern_management/public/plugin.ts +++ b/src/plugins/index_pattern_management/public/plugin.ts @@ -20,7 +20,7 @@ import { i18n } from '@kbn/i18n'; import { PluginInitializerContext, CoreSetup, CoreStart, Plugin } from 'src/core/public'; import { DataPublicPluginStart } from 'src/plugins/data/public'; -import { KibanaLegacySetup } from '../../kibana_legacy/public'; +import { UrlForwardingSetup } from '../../url_forwarding/public'; import { IndexPatternManagementService, IndexPatternManagementServiceSetup, @@ -31,7 +31,7 @@ import { ManagementSetup } from '../../management/public'; export interface IndexPatternManagementSetupDependencies { management: ManagementSetup; - kibanaLegacy: KibanaLegacySetup; + urlForwarding: UrlForwardingSetup; } export interface IndexPatternManagementStartDependencies { @@ -62,7 +62,7 @@ export class IndexPatternManagementPlugin public setup( core: CoreSetup, - { management, kibanaLegacy }: IndexPatternManagementSetupDependencies + { management, urlForwarding }: IndexPatternManagementSetupDependencies ) { const kibanaSection = management.sections.section.kibana; @@ -73,8 +73,8 @@ export class IndexPatternManagementPlugin const newAppPath = `management/kibana/${IPM_APP_ID}`; const legacyPatternsPath = 'management/kibana/index_patterns'; - kibanaLegacy.forwardApp('management/kibana/index_pattern', newAppPath, (path) => '/create'); - kibanaLegacy.forwardApp(legacyPatternsPath, newAppPath, (path) => { + urlForwarding.forwardApp('management/kibana/index_pattern', newAppPath, (path) => '/create'); + urlForwarding.forwardApp(legacyPatternsPath, newAppPath, (path) => { const pathInApp = path.substr(legacyPatternsPath.length + 1); return pathInApp && `/patterns${pathInApp}`; }); diff --git a/src/plugins/kibana_legacy/README.md b/src/plugins/kibana_legacy/README.md index 82bf3270589db..d66938cca6d13 100644 --- a/src/plugins/kibana_legacy/README.md +++ b/src/plugins/kibana_legacy/README.md @@ -1,6 +1,7 @@ # kibana-legacy -This plugin will contain several helpers and services to integrate pieces of the legacy Kibana app with the new Kibana platform. +This plugin contains several helpers and services to integrate pieces of the legacy Kibana app with the new Kibana platform. -Currently, the only service offered is the ability to register apps which are rendered in the legacy "kibana" plugin. +This plugin will be removed once all parts of legacy Kibana are removed from other plugins. +All of this plugin should be considered deprecated. New code should never integrate with the services provided from this plugin. \ No newline at end of file diff --git a/src/plugins/kibana_legacy/kibana.json b/src/plugins/kibana_legacy/kibana.json index 79264d95dcc27..e96b4859a36d0 100644 --- a/src/plugins/kibana_legacy/kibana.json +++ b/src/plugins/kibana_legacy/kibana.json @@ -2,6 +2,5 @@ "id": "kibanaLegacy", "version": "kibana", "server": true, - "ui": true, - "extraPublicDirs": ["common", "common/kbn_base_url"] + "ui": true } diff --git a/src/plugins/kibana_legacy/public/index.ts b/src/plugins/kibana_legacy/public/index.ts index 27b940b0a456b..030dfd585fefb 100644 --- a/src/plugins/kibana_legacy/public/index.ts +++ b/src/plugins/kibana_legacy/public/index.ts @@ -24,7 +24,6 @@ export const plugin = (initializerContext: PluginInitializerContext) => new KibanaLegacyPlugin(initializerContext); export * from './plugin'; -export { kbnBaseUrl, migrateLegacyQuery } from '../common'; export { initAngularBootstrap } from './angular_bootstrap'; export { PaginateDirectiveProvider, PaginateControlsDirectiveProvider } from './paginate/paginate'; diff --git a/src/plugins/kibana_legacy/public/mocks.ts b/src/plugins/kibana_legacy/public/mocks.ts index a3cdb2106523c..f3aa015b6000b 100644 --- a/src/plugins/kibana_legacy/public/mocks.ts +++ b/src/plugins/kibana_legacy/public/mocks.ts @@ -22,12 +22,9 @@ import { KibanaLegacyPlugin } from './plugin'; export type Setup = jest.Mocked>; export type Start = jest.Mocked>; -const createSetupContract = (): Setup => ({ - forwardApp: jest.fn(), -}); +const createSetupContract = (): Setup => ({}); const createStartContract = (): Start => ({ - getForwards: jest.fn(), config: { defaultAppId: 'home', }, @@ -35,8 +32,6 @@ const createStartContract = (): Start => ({ turnHideWriteControlsOn: jest.fn(), getHideWriteControls: jest.fn(), }, - navigateToDefaultApp: jest.fn(), - navigateToLegacyKibanaUrl: jest.fn(), loadFontAwesome: jest.fn(), }); diff --git a/src/plugins/kibana_legacy/public/plugin.ts b/src/plugins/kibana_legacy/public/plugin.ts index 59ce88c07f4f4..8e62411fc34e9 100644 --- a/src/plugins/kibana_legacy/public/plugin.ts +++ b/src/plugins/kibana_legacy/public/plugin.ts @@ -18,78 +18,18 @@ */ import { PluginInitializerContext, CoreStart, CoreSetup } from 'kibana/public'; -import { Subscription } from 'rxjs'; import { ConfigSchema } from '../config'; import { getDashboardConfig } from './dashboard_config'; -import { navigateToDefaultApp } from './navigate_to_default_app'; -import { createLegacyUrlForwardApp } from './forward_app'; import { injectHeaderStyle } from './utils/inject_header_style'; -import { navigateToLegacyKibanaUrl } from './forward_app/navigate_to_legacy_kibana_url'; - -export interface ForwardDefinition { - legacyAppId: string; - newAppId: string; - rewritePath: (legacyPath: string) => string; -} export class KibanaLegacyPlugin { - private forwardDefinitions: ForwardDefinition[] = []; - private currentAppId: string | undefined; - private currentAppIdSubscription: Subscription | undefined; - constructor(private readonly initializerContext: PluginInitializerContext) {} public setup(core: CoreSetup<{}, KibanaLegacyStart>) { - core.application.register(createLegacyUrlForwardApp(core, this.forwardDefinitions)); - return { - /** - * Forwards URLs within the legacy `kibana` app to a new platform application. - * - * @param legacyAppId The name of the old app to forward URLs from - * @param newAppId The name of the new app that handles the URLs now - * @param rewritePath Function to rewrite the legacy sub path of the app to the new path in the core app. - * If none is provided, it will just strip the prefix of the legacyAppId away - * - * path into the new path - * - * Example usage: - * ``` - * kibanaLegacy.forwardApp( - * 'old', - * 'new', - * path => { - * const [, id] = /old/item\/(.*)$/.exec(path) || []; - * if (!id) { - * return '#/home'; - * } - * return '#/items/${id}'; - * } - * ); - * ``` - * This will cause the following redirects: - * - * * app/kibana#/old/ -> app/new#/home - * * app/kibana#/old/item/123 -> app/new#/items/123 - * - */ - forwardApp: ( - legacyAppId: string, - newAppId: string, - rewritePath?: (legacyPath: string) => string - ) => { - this.forwardDefinitions.push({ - legacyAppId, - newAppId, - rewritePath: rewritePath || ((path) => `#${path.replace(`/${legacyAppId}`, '') || '/'}`), - }); - }, - }; + return {}; } public start({ application, http: { basePath }, uiSettings }: CoreStart) { - this.currentAppIdSubscription = application.currentAppId$.subscribe((currentAppId) => { - this.currentAppId = currentAppId; - }); injectHeaderStyle(uiSettings); return { /** @@ -97,31 +37,6 @@ export class KibanaLegacyPlugin { * @deprecated */ dashboardConfig: getDashboardConfig(!application.capabilities.dashboard.showWriteControls), - /** - * Navigates to the app defined as kibana.defaultAppId. - * This takes redirects into account and uses the right mechanism to navigate. - */ - navigateToDefaultApp: ( - { overwriteHash }: { overwriteHash: boolean } = { overwriteHash: true } - ) => { - navigateToDefaultApp( - this.initializerContext.config.get().defaultAppId, - this.forwardDefinitions, - application, - basePath, - this.currentAppId, - overwriteHash - ); - }, - /** - * Resolves the provided hash using the registered forwards and navigates to the target app. - * If a navigation happened, `{ navigated: true }` will be returned. - * If no matching forward is found, `{ navigated: false }` will be returned. - * @param hash - */ - navigateToLegacyKibanaUrl: (hash: string) => { - return navigateToLegacyKibanaUrl(hash, this.forwardDefinitions, basePath, application); - }, /** * Loads the font-awesome icon font. Should be removed once the last consumer has migrated to EUI * @deprecated @@ -129,11 +44,6 @@ export class KibanaLegacyPlugin { loadFontAwesome: async () => { await import('./font_awesome'); }, - /** - * @deprecated - * Just exported for wiring up with legacy platform, should not be used. - */ - getForwards: () => this.forwardDefinitions, /** * @deprecated * Just exported for wiring up with dashboard mode, should not be used. @@ -141,12 +51,6 @@ export class KibanaLegacyPlugin { config: this.initializerContext.config.get(), }; } - - public stop() { - if (this.currentAppIdSubscription) { - this.currentAppIdSubscription.unsubscribe(); - } - } } export type KibanaLegacySetup = ReturnType; diff --git a/src/plugins/kibana_legacy/public/utils/index.ts b/src/plugins/kibana_legacy/public/utils/index.ts index a32cd5e40a047..590a75ffeed9e 100644 --- a/src/plugins/kibana_legacy/public/utils/index.ts +++ b/src/plugins/kibana_legacy/public/utils/index.ts @@ -18,7 +18,6 @@ */ export * from './system_api'; -export * from './normalize_path'; // @ts-ignore export { KbnAccessibleClickProvider } from './kbn_accessible_click'; // @ts-ignore diff --git a/src/plugins/kibana_legacy/server/index.ts b/src/plugins/kibana_legacy/server/index.ts index 3ddcac1517f74..c447f44c16a89 100644 --- a/src/plugins/kibana_legacy/server/index.ts +++ b/src/plugins/kibana_legacy/server/index.ts @@ -50,8 +50,6 @@ export const config: PluginConfigDescriptor = { ], }; -export { kbnBaseUrl, migrateLegacyQuery } from '../common'; - class Plugin { public setup(core: CoreSetup) {} diff --git a/src/plugins/management/kibana.json b/src/plugins/management/kibana.json index 1a9e6be46bd55..6c8574f024229 100644 --- a/src/plugins/management/kibana.json +++ b/src/plugins/management/kibana.json @@ -3,7 +3,6 @@ "version": "kibana", "server": true, "ui": true, - "requiredPlugins": ["kibanaLegacy"], "optionalPlugins": ["home"], "requiredBundles": ["kibanaReact", "kibanaUtils", "home"] } diff --git a/src/plugins/url_forwarding/README.md b/src/plugins/url_forwarding/README.md new file mode 100644 index 0000000000000..5c5501cc019f9 --- /dev/null +++ b/src/plugins/url_forwarding/README.md @@ -0,0 +1,3 @@ +# url-forwarding + +This plugins contains helpers to redirect legacy URLs. It can be used to forward old URLs to their new counterparts. diff --git a/src/plugins/url_forwarding/kibana.json b/src/plugins/url_forwarding/kibana.json new file mode 100644 index 0000000000000..4f534c1219b34 --- /dev/null +++ b/src/plugins/url_forwarding/kibana.json @@ -0,0 +1,7 @@ +{ + "id": "urlForwarding", + "version": "kibana", + "server": false, + "ui": true, + "requiredPlugins": ["kibanaLegacy"] +} diff --git a/src/plugins/kibana_legacy/public/forward_app/forward_app.ts b/src/plugins/url_forwarding/public/forward_app/forward_app.ts similarity index 94% rename from src/plugins/kibana_legacy/public/forward_app/forward_app.ts rename to src/plugins/url_forwarding/public/forward_app/forward_app.ts index b425091dfbcd9..967b18769ebc6 100644 --- a/src/plugins/kibana_legacy/public/forward_app/forward_app.ts +++ b/src/plugins/url_forwarding/public/forward_app/forward_app.ts @@ -20,10 +20,10 @@ import { App, AppMountParameters, CoreSetup } from 'kibana/public'; import { AppNavLinkStatus } from '../../../../core/public'; import { navigateToLegacyKibanaUrl } from './navigate_to_legacy_kibana_url'; -import { ForwardDefinition, KibanaLegacyStart } from '../plugin'; +import { ForwardDefinition, UrlForwardingStart } from '../plugin'; export const createLegacyUrlForwardApp = ( - core: CoreSetup<{}, KibanaLegacyStart>, + core: CoreSetup<{}, UrlForwardingStart>, forwards: ForwardDefinition[] ): App => ({ id: 'kibana', diff --git a/src/plugins/kibana_legacy/public/forward_app/index.ts b/src/plugins/url_forwarding/public/forward_app/index.ts similarity index 100% rename from src/plugins/kibana_legacy/public/forward_app/index.ts rename to src/plugins/url_forwarding/public/forward_app/index.ts diff --git a/src/plugins/kibana_legacy/public/forward_app/navigate_to_legacy_kibana_url.test.ts b/src/plugins/url_forwarding/public/forward_app/navigate_to_legacy_kibana_url.test.ts similarity index 100% rename from src/plugins/kibana_legacy/public/forward_app/navigate_to_legacy_kibana_url.test.ts rename to src/plugins/url_forwarding/public/forward_app/navigate_to_legacy_kibana_url.test.ts diff --git a/src/plugins/kibana_legacy/public/forward_app/navigate_to_legacy_kibana_url.ts b/src/plugins/url_forwarding/public/forward_app/navigate_to_legacy_kibana_url.ts similarity index 96% rename from src/plugins/kibana_legacy/public/forward_app/navigate_to_legacy_kibana_url.ts rename to src/plugins/url_forwarding/public/forward_app/navigate_to_legacy_kibana_url.ts index 1df991f66747c..1677b01e7aa4f 100644 --- a/src/plugins/kibana_legacy/public/forward_app/navigate_to_legacy_kibana_url.ts +++ b/src/plugins/url_forwarding/public/forward_app/navigate_to_legacy_kibana_url.ts @@ -19,7 +19,7 @@ import { ApplicationStart, IBasePath } from 'kibana/public'; import { ForwardDefinition } from '../index'; -import { normalizePath } from '../utils/normalize_path'; +import { normalizePath } from './normalize_path'; export const navigateToLegacyKibanaUrl = ( path: string, diff --git a/src/plugins/kibana_legacy/public/utils/normalize_path.ts b/src/plugins/url_forwarding/public/forward_app/normalize_path.ts similarity index 100% rename from src/plugins/kibana_legacy/public/utils/normalize_path.ts rename to src/plugins/url_forwarding/public/forward_app/normalize_path.ts diff --git a/src/plugins/kibana_legacy/common/index.ts b/src/plugins/url_forwarding/public/index.ts similarity index 85% rename from src/plugins/kibana_legacy/common/index.ts rename to src/plugins/url_forwarding/public/index.ts index 9c16d7b273862..5fc3f0bea4d3e 100644 --- a/src/plugins/kibana_legacy/common/index.ts +++ b/src/plugins/url_forwarding/public/index.ts @@ -17,5 +17,8 @@ * under the License. */ -export * from './kbn_base_url'; -export * from './migrate_legacy_query'; +import { UrlForwardingPlugin } from './plugin'; + +export const plugin = () => new UrlForwardingPlugin(); + +export * from './plugin'; diff --git a/src/plugins/kibana_legacy/common/kbn_base_url.ts b/src/plugins/url_forwarding/public/mocks.ts similarity index 60% rename from src/plugins/kibana_legacy/common/kbn_base_url.ts rename to src/plugins/url_forwarding/public/mocks.ts index 69711626750ea..5e32d9b1896bc 100644 --- a/src/plugins/kibana_legacy/common/kbn_base_url.ts +++ b/src/plugins/url_forwarding/public/mocks.ts @@ -17,4 +17,22 @@ * under the License. */ -export const kbnBaseUrl = '/app/kibana'; +import { UrlForwardingPlugin } from './plugin'; + +export type Setup = jest.Mocked>; +export type Start = jest.Mocked>; + +const createSetupContract = (): Setup => ({ + forwardApp: jest.fn(), +}); + +const createStartContract = (): Start => ({ + getForwards: jest.fn(), + navigateToDefaultApp: jest.fn(), + navigateToLegacyKibanaUrl: jest.fn(), +}); + +export const urlForwardingPluginMock = { + createSetupContract, + createStartContract, +}; diff --git a/src/plugins/kibana_legacy/public/navigate_to_default_app.ts b/src/plugins/url_forwarding/public/navigate_to_default_app.ts similarity index 100% rename from src/plugins/kibana_legacy/public/navigate_to_default_app.ts rename to src/plugins/url_forwarding/public/navigate_to_default_app.ts diff --git a/src/plugins/url_forwarding/public/plugin.ts b/src/plugins/url_forwarding/public/plugin.ts new file mode 100644 index 0000000000000..8ef23fb2c840e --- /dev/null +++ b/src/plugins/url_forwarding/public/plugin.ts @@ -0,0 +1,134 @@ +/* + * 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 { CoreStart, CoreSetup } from 'kibana/public'; +import { KibanaLegacyStart } from 'src/plugins/kibana_legacy/public'; +import { Subscription } from 'rxjs'; +import { navigateToDefaultApp } from './navigate_to_default_app'; +import { createLegacyUrlForwardApp } from './forward_app'; +import { navigateToLegacyKibanaUrl } from './forward_app/navigate_to_legacy_kibana_url'; + +export interface ForwardDefinition { + legacyAppId: string; + newAppId: string; + rewritePath: (legacyPath: string) => string; +} + +export class UrlForwardingPlugin { + private forwardDefinitions: ForwardDefinition[] = []; + private currentAppId: string | undefined; + private currentAppIdSubscription: Subscription | undefined; + + public setup(core: CoreSetup<{}, UrlForwardingStart>) { + core.application.register(createLegacyUrlForwardApp(core, this.forwardDefinitions)); + return { + /** + * Forwards URLs within the legacy `kibana` app to a new platform application. + * + * @param legacyAppId The name of the old app to forward URLs from + * @param newAppId The name of the new app that handles the URLs now + * @param rewritePath Function to rewrite the legacy sub path of the app to the new path in the core app. + * If none is provided, it will just strip the prefix of the legacyAppId away + * + * path into the new path + * + * Example usage: + * ``` + * urlForwarding.forwardApp( + * 'old', + * 'new', + * path => { + * const [, id] = /old/item\/(.*)$/.exec(path) || []; + * if (!id) { + * return '#/home'; + * } + * return '#/items/${id}'; + * } + * ); + * ``` + * This will cause the following redirects: + * + * * app/kibana#/old/ -> app/new#/home + * * app/kibana#/old/item/123 -> app/new#/items/123 + * + */ + forwardApp: ( + legacyAppId: string, + newAppId: string, + rewritePath?: (legacyPath: string) => string + ) => { + this.forwardDefinitions.push({ + legacyAppId, + newAppId, + rewritePath: rewritePath || ((path) => `#${path.replace(`/${legacyAppId}`, '') || '/'}`), + }); + }, + }; + } + + public start( + { application, http: { basePath }, uiSettings }: CoreStart, + { kibanaLegacy }: { kibanaLegacy: KibanaLegacyStart } + ) { + this.currentAppIdSubscription = application.currentAppId$.subscribe((currentAppId) => { + this.currentAppId = currentAppId; + }); + return { + /** + * Navigates to the app defined as kibana.defaultAppId. + * This takes redirects into account and uses the right mechanism to navigate. + */ + navigateToDefaultApp: ( + { overwriteHash }: { overwriteHash: boolean } = { overwriteHash: true } + ) => { + navigateToDefaultApp( + kibanaLegacy.config.defaultAppId, + this.forwardDefinitions, + application, + basePath, + this.currentAppId, + overwriteHash + ); + }, + /** + * Resolves the provided hash using the registered forwards and navigates to the target app. + * If a navigation happened, `{ navigated: true }` will be returned. + * If no matching forward is found, `{ navigated: false }` will be returned. + * @param hash + */ + navigateToLegacyKibanaUrl: (hash: string) => { + return navigateToLegacyKibanaUrl(hash, this.forwardDefinitions, basePath, application); + }, + /** + * @deprecated + * Just exported for wiring up with legacy platform, should not be used. + */ + getForwards: () => this.forwardDefinitions, + }; + } + + public stop() { + if (this.currentAppIdSubscription) { + this.currentAppIdSubscription.unsubscribe(); + } + } +} + +export type UrlForwardingSetup = ReturnType; +export type UrlForwardingStart = ReturnType; diff --git a/src/plugins/visualize/kibana.json b/src/plugins/visualize/kibana.json index 29fcd30184cb2..318a1562efdfe 100644 --- a/src/plugins/visualize/kibana.json +++ b/src/plugins/visualize/kibana.json @@ -5,7 +5,7 @@ "ui": true, "requiredPlugins": [ "data", - "kibanaLegacy", + "urlForwarding", "navigation", "savedObjects", "visualizations", diff --git a/src/plugins/visualize/public/application/components/visualize_no_match.tsx b/src/plugins/visualize/public/application/components/visualize_no_match.tsx index 7776c5e8ce486..98f22f25c666e 100644 --- a/src/plugins/visualize/public/application/components/visualize_no_match.tsx +++ b/src/plugins/visualize/public/application/components/visualize_no_match.tsx @@ -34,7 +34,7 @@ export const VisualizeNoMatch = () => { useEffect(() => { services.restorePreviousUrl(); - const { navigated } = services.kibanaLegacy.navigateToLegacyKibanaUrl( + const { navigated } = services.urlForwarding.navigateToLegacyKibanaUrl( services.history.location.pathname ); diff --git a/src/plugins/visualize/public/application/types.ts b/src/plugins/visualize/public/application/types.ts index 0a12dbc22a744..4bdd19113dddc 100644 --- a/src/plugins/visualize/public/application/types.ts +++ b/src/plugins/visualize/public/application/types.ts @@ -43,7 +43,7 @@ import { import { SharePluginStart } from 'src/plugins/share/public'; import { SavedObjectsStart, SavedObject } from 'src/plugins/saved_objects/public'; import { EmbeddableStart } from 'src/plugins/embeddable/public'; -import { KibanaLegacyStart } from 'src/plugins/kibana_legacy/public'; +import { UrlForwardingStart } from 'src/plugins/url_forwarding/public'; import { DashboardStart } from '../../../dashboard/public'; export type PureVisState = SavedVisState; @@ -95,7 +95,7 @@ export interface VisualizeServices extends CoreStart { embeddable: EmbeddableStart; history: History; kbnUrlStateStorage: IKbnUrlStateStorage; - kibanaLegacy: KibanaLegacyStart; + urlForwarding: UrlForwardingStart; pluginInitializerContext: PluginInitializerContext; chrome: ChromeStart; data: DataPublicPluginStart; diff --git a/src/plugins/visualize/public/application/utils/migrate_legacy_query.ts b/src/plugins/visualize/public/application/utils/migrate_legacy_query.ts new file mode 100644 index 0000000000000..8d9b50d5a66b2 --- /dev/null +++ b/src/plugins/visualize/public/application/utils/migrate_legacy_query.ts @@ -0,0 +1,37 @@ +/* + * 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 { has } from 'lodash'; +import { Query } from 'src/plugins/data/public'; + +/** + * Creates a standardized query object from old queries that were either strings or pure ES query DSL + * + * @param query - a legacy query, what used to be stored in SearchSource's query property + * @return Object + */ + +export function migrateLegacyQuery(query: Query | { [key: string]: any } | string): Query { + // Lucene was the only option before, so language-less queries are all lucene + if (!has(query, 'language')) { + return { query, language: 'lucene' }; + } + + return query as Query; +} diff --git a/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.tsx b/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.tsx index 935d4b26c98c9..24381ecfc9e2d 100644 --- a/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.tsx +++ b/src/plugins/visualize/public/application/utils/use/use_visualize_app_state.tsx @@ -24,7 +24,7 @@ import { EventEmitter } from 'events'; import { i18n } from '@kbn/i18n'; import { MarkdownSimple, toMountPoint } from '../../../../../kibana_react/public'; -import { migrateLegacyQuery } from '../../../../../kibana_legacy/public'; +import { migrateLegacyQuery } from '../migrate_legacy_query'; import { esFilters, connectToQueryState } from '../../../../../data/public'; import { VisualizeServices, diff --git a/src/plugins/visualize/public/plugin.ts b/src/plugins/visualize/public/plugin.ts index 7e5cafd3ceecc..95d5343d5d695 100644 --- a/src/plugins/visualize/public/plugin.ts +++ b/src/plugins/visualize/public/plugin.ts @@ -40,7 +40,7 @@ import { import { DataPublicPluginStart, DataPublicPluginSetup, esFilters } from '../../data/public'; import { NavigationPublicPluginStart as NavigationStart } from '../../navigation/public'; import { SharePluginStart, SharePluginSetup } from '../../share/public'; -import { KibanaLegacySetup, KibanaLegacyStart } from '../../kibana_legacy/public'; +import { UrlForwardingSetup, UrlForwardingStart } from '../../url_forwarding/public'; import { VisualizationsStart } from '../../visualizations/public'; import { VisualizeConstants } from './application/visualize_constants'; import { FeatureCatalogueCategory, HomePublicPluginSetup } from '../../home/public'; @@ -66,7 +66,7 @@ export interface VisualizePluginStartDependencies { share?: SharePluginStart; visualizations: VisualizationsStart; embeddable: EmbeddableStart; - kibanaLegacy: KibanaLegacyStart; + urlForwarding: UrlForwardingStart; savedObjects: SavedObjectsStart; dashboard: DashboardStart; uiActions: UiActionsStart; @@ -74,7 +74,7 @@ export interface VisualizePluginStartDependencies { export interface VisualizePluginSetupDependencies { home?: HomePublicPluginSetup; - kibanaLegacy: KibanaLegacySetup; + urlForwarding: UrlForwardingSetup; data: DataPublicPluginSetup; share?: SharePluginSetup; } @@ -90,7 +90,7 @@ export class VisualizePlugin public async setup( core: CoreSetup, - { home, kibanaLegacy, data, share }: VisualizePluginSetupDependencies + { home, urlForwarding, data, share }: VisualizePluginSetupDependencies ) { const { appMounted, @@ -177,7 +177,7 @@ export class VisualizePlugin useHash: coreStart.uiSettings.get('state:storeInSessionStorage'), ...withNotifyOnErrors(coreStart.notifications.toasts), }), - kibanaLegacy: pluginsStart.kibanaLegacy, + urlForwarding: pluginsStart.urlForwarding, pluginInitializerContext: this.initializerContext, chrome: coreStart.chrome, data: pluginsStart.data, @@ -209,7 +209,7 @@ export class VisualizePlugin }, }); - kibanaLegacy.forwardApp('visualize', 'visualize'); + urlForwarding.forwardApp('visualize', 'visualize'); if (home) { home.featureCatalogue.register({ diff --git a/x-pack/package.json b/x-pack/package.json index 3a074ba1f1d7d..1e2fa4d7ee550 100644 --- a/x-pack/package.json +++ b/x-pack/package.json @@ -207,7 +207,7 @@ "mocha": "^7.1.1", "mocha-junit-reporter": "^1.23.1", "mochawesome": "^4.1.0", - "mochawesome-merge": "^2.0.1", + "mochawesome-merge": "^4.1.0", "mustache": "^2.3.0", "mutation-observer": "^1.0.3", "node-fetch": "^2.6.0", @@ -268,7 +268,7 @@ "vinyl-fs": "^3.0.3", "whatwg-fetch": "^3.0.0", "xml-crypto": "^1.4.0", - "yargs": "4.8.1" + "yargs": "^15.4.1" }, "dependencies": { "@babel/core": "^7.11.1", diff --git a/x-pack/plugins/actions/README.md b/x-pack/plugins/actions/README.md index 3bc8acead6c13..c55b21b2f9029 100644 --- a/x-pack/plugins/actions/README.md +++ b/x-pack/plugins/actions/README.md @@ -331,15 +331,17 @@ const result = await actionsClient.execute({ Kibana ships with a set of built-in action types: -| Type | Id | Description | -| ------------------------- | ------------- | ------------------------------------------------------------------ | -| [Server log](#server-log) | `.server-log` | Logs messages to the Kibana log using Kibana's logger | -| [Email](#email) | `.email` | Sends an email using SMTP | -| [Slack](#slack) | `.slack` | Posts a message to a slack channel | -| [Index](#index) | `.index` | Indexes document(s) into Elasticsearch | -| [Webhook](#webhook) | `.webhook` | Send a payload to a web service using HTTP POST or PUT | -| [PagerDuty](#pagerduty) | `.pagerduty` | Trigger, resolve, or acknowlege an incident to a PagerDuty service | -| [ServiceNow](#servicenow) | `.servicenow` | Create or update an incident to a ServiceNow instance | +| Type | Id | Description | +| ------------------------------- | ------------- | ------------------------------------------------------------------ | +| [Server log](#server-log) | `.server-log` | Logs messages to the Kibana log using Kibana's logger | +| [Email](#email) | `.email` | Sends an email using SMTP | +| [Slack](#slack) | `.slack` | Posts a message to a slack channel | +| [Index](#index) | `.index` | Indexes document(s) into Elasticsearch | +| [Webhook](#webhook) | `.webhook` | Send a payload to a web service using HTTP POST or PUT | +| [PagerDuty](#pagerduty) | `.pagerduty` | Trigger, resolve, or acknowlege an incident to a PagerDuty service | +| [ServiceNow](#servicenow) | `.servicenow` | Create or update an incident to a ServiceNow instance | +| [Jira](#jira) | `.jira` | Create or update an issue to a Jira instance | +| [IBM Resilient](#ibm-resilient) | `.resilient` | Create or update an incident to a IBM Resilient instance | --- @@ -561,8 +563,8 @@ The ServiceNow action uses the [V2 Table API](https://developer.servicenow.com/a | Property | Description | Type | | ------------- | ------------------------------------------------------------------------------------------------------------------------- | --------------------- | | savedObjectId | The id of the saved object. | string | -| title | The title of the case. | string _(optional)_ | -| description | The description of the case. | string _(optional)_ | +| title | The title of the incident. | string _(optional)_ | +| description | The description of the incident. | string _(optional)_ | | comment | A comment. | string _(optional)_ | | comments | The comments of the case. A comment is of the form `{ commentId: string, version: string, comment: string }`. | object[] _(optional)_ | | externalId | The id of the incident in ServiceNow. If presented the incident will be update. Otherwise a new incident will be created. | string _(optional)_ | @@ -601,16 +603,16 @@ The Jira action uses the [V2 API](https://developer.atlassian.com/cloud/jira/pla #### `subActionParams (pushToService)` -| Property | Description | Type | -| ------------- | ------------------------------------------------------------------------------------------------------------------- | --------------------- | -| savedObjectId | The id of the saved object | string | -| title | The title of the case | string _(optional)_ | -| description | The description of the case | string _(optional)_ | -| externalId | The id of the incident in Jira. If presented the incident will be update. Otherwise a new incident will be created. | string _(optional)_ | -| issueType | The id of the issue type in Jira. | string _(optional)_ | -| priority | The name of the priority in Jira. Example: `Medium`. | string _(optional)_ | -| labels | An array of labels. | string[] _(optional)_ | -| comments | The comments of the case. A comment is of the form `{ commentId: string, version: string, comment: string }` | object[] _(optional)_ | +| Property | Description | Type | +| ------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------- | +| savedObjectId | The id of the saved object | string | +| title | The title of the issue | string _(optional)_ | +| description | The description of the issue | string _(optional)_ | +| externalId | The id of the issue in Jira. If presented the incident will be update. Otherwise a new incident will be created. | string _(optional)_ | +| issueType | The id of the issue type in Jira. | string _(optional)_ | +| priority | The name of the priority in Jira. Example: `Medium`. | string _(optional)_ | +| labels | An array of labels. | string[] _(optional)_ | +| comments | The comments of the case. A comment is of the form `{ commentId: string, version: string, comment: string }` | object[] _(optional)_ | #### `subActionParams (issueTypes)` @@ -628,10 +630,10 @@ ID: `.resilient` ### `config` -| Property | Description | Type | -| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------ | -| apiUrl | IBM Resilient instance URL. | string | -| incidentConfiguration | Case configuration object. The object should contain an attribute called `mapping`. A `mapping` is an array of objects. Each mapping object should be of the form `{ source: string, target: string, actionType: string }`. `source` is the Case field. `target` is the Jira field where `source` will be mapped to. `actionType` can be one of `nothing`, `overwrite` or `append`. For example the `{ source: 'title', target: 'summary', actionType: 'overwrite' }` record, inside mapping array, means that the title of a case will be mapped to the short description of an incident in IBM Resilient and will be overwrite on each update. | object | +| Property | Description | Type | +| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | +| apiUrl | IBM Resilient instance URL. | string | +| incidentConfiguration | Optional property and specific to **Cases only**. If defined, the object should contain an attribute called `mapping`. A `mapping` is an array of objects. Each mapping object should be of the form `{ source: string, target: string, actionType: string }`. `source` is the Case field. `target` is the Jira field where `source` will be mapped to. `actionType` can be one of `nothing`, `overwrite` or `append`. For example the `{ source: 'title', target: 'summary', actionType: 'overwrite' }` record, inside mapping array, means that the title of a case will be mapped to the short description of an incident in IBM Resilient and will be overwrite on each update. | object | ### `secrets` @@ -652,10 +654,12 @@ ID: `.resilient` | Property | Description | Type | | ------------- | ---------------------------------------------------------------------------------------------------------------------------- | --------------------- | | savedObjectId | The id of the saved object | string | -| title | The title of the case | string _(optional)_ | -| description | The description of the case | string _(optional)_ | -| comments | The comments of the case. A comment is of the form `{ commentId: string, version: string, comment: string }` | object[] _(optional)_ | +| title | The title of the incident | string _(optional)_ | +| description | The description of the incident | string _(optional)_ | +| comments | The comments of the incident. A comment is of the form `{ commentId: string, version: string, comment: string }` | object[] _(optional)_ | | externalId | The id of the incident in IBM Resilient. If presented the incident will be update. Otherwise a new incident will be created. | string _(optional)_ | +| incidentTypes | An array with the ids of IBM Resilient incident types. | number[] _(optional)_ | +| severityCode | IBM Resilient id of the severity code. | number _(optional)_ | # Command Line Utility diff --git a/x-pack/plugins/actions/server/builtin_action_types/case/api.ts b/x-pack/plugins/actions/server/builtin_action_types/case/api.ts deleted file mode 100644 index de4b7edaed3da..0000000000000 --- a/x-pack/plugins/actions/server/builtin_action_types/case/api.ts +++ /dev/null @@ -1,93 +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 { - ExternalServiceApi, - ExternalServiceParams, - PushToServiceResponse, - GetIncidentApiHandlerArgs, - HandshakeApiHandlerArgs, - PushToServiceApiHandlerArgs, -} from './types'; -import { prepareFieldsForTransformation, transformFields, transformComments } from './utils'; - -const handshakeHandler = async ({ - externalService, - mapping, - params, -}: HandshakeApiHandlerArgs) => {}; -const getIncidentHandler = async ({ - externalService, - mapping, - params, -}: GetIncidentApiHandlerArgs) => {}; - -const pushToServiceHandler = async ({ - externalService, - mapping, - params, -}: PushToServiceApiHandlerArgs): Promise => { - const { externalId, comments } = params; - const updateIncident = externalId ? true : false; - const defaultPipes = updateIncident ? ['informationUpdated'] : ['informationCreated']; - let currentIncident: ExternalServiceParams | undefined; - let res: PushToServiceResponse; - - if (externalId) { - currentIncident = await externalService.getIncident(externalId); - } - - const fields = prepareFieldsForTransformation({ - externalCase: params.externalCase, - mapping, - defaultPipes, - }); - - const incident = transformFields({ - params, - fields, - currentIncident, - }); - - if (updateIncident) { - res = await externalService.updateIncident({ incidentId: externalId, incident }); - } else { - res = await externalService.createIncident({ incident }); - } - - if ( - comments && - Array.isArray(comments) && - comments.length > 0 && - mapping.get('comments')?.actionType !== 'nothing' - ) { - const commentsTransformed = transformComments(comments, ['informationAdded']); - - res.comments = []; - for (const currentComment of commentsTransformed) { - const comment = await externalService.createComment({ - incidentId: res.id, - comment: currentComment, - field: mapping.get('comments')?.target ?? 'comments', - }); - res.comments = [ - ...(res.comments ?? []), - { - commentId: comment.commentId, - pushedDate: comment.pushedDate, - }, - ]; - } - } - - return res; -}; - -export const api: ExternalServiceApi = { - handshake: handshakeHandler, - pushToService: pushToServiceHandler, - getIncident: getIncidentHandler, -}; diff --git a/x-pack/plugins/actions/server/builtin_action_types/case/common_schema.ts b/x-pack/plugins/actions/server/builtin_action_types/case/common_schema.ts deleted file mode 100644 index 5a23eb89339e6..0000000000000 --- a/x-pack/plugins/actions/server/builtin_action_types/case/common_schema.ts +++ /dev/null @@ -1,43 +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 { schema } from '@kbn/config-schema'; - -export const MappingActionType = schema.oneOf([ - schema.literal('nothing'), - schema.literal('overwrite'), - schema.literal('append'), -]); - -export const MapRecordSchema = schema.object({ - source: schema.string(), - target: schema.string(), - actionType: MappingActionType, -}); - -export const IncidentConfigurationSchema = schema.object({ - mapping: schema.arrayOf(MapRecordSchema), -}); - -export const UserSchema = schema.object({ - fullName: schema.nullable(schema.string()), - username: schema.nullable(schema.string()), -}); - -export const EntityInformation = { - createdAt: schema.nullable(schema.string()), - createdBy: schema.nullable(UserSchema), - updatedAt: schema.nullable(schema.string()), - updatedBy: schema.nullable(UserSchema), -}; - -export const EntityInformationSchema = schema.object(EntityInformation); - -export const CommentSchema = schema.object({ - commentId: schema.string(), - comment: schema.string(), - ...EntityInformation, -}); diff --git a/x-pack/plugins/actions/server/builtin_action_types/case/common_types.ts b/x-pack/plugins/actions/server/builtin_action_types/case/common_types.ts deleted file mode 100644 index cca83fb88ca92..0000000000000 --- a/x-pack/plugins/actions/server/builtin_action_types/case/common_types.ts +++ /dev/null @@ -1,48 +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 { TypeOf } from '@kbn/config-schema'; -import { - IncidentConfigurationSchema, - MapRecordSchema, - CommentSchema, - EntityInformationSchema, -} from './common_schema'; - -export interface CreateCommentRequest { - [key: string]: string; -} - -export type IncidentConfiguration = TypeOf; -export type MapRecord = TypeOf; -export type Comment = TypeOf; -export type EntityInformation = TypeOf; - -export interface ExternalServiceCommentResponse { - commentId: string; - pushedDate: string; - externalCommentId?: string; -} - -export interface PipedField { - key: string; - value: string; - actionType: string; - pipes: string[]; -} - -export interface TransformFieldsArgs { - params: P; - fields: PipedField[]; - currentIncident?: S; -} - -export interface TransformerArgs { - value: string; - date?: string; - user?: string; - previousValue?: string; -} diff --git a/x-pack/plugins/actions/server/builtin_action_types/case/schema.ts b/x-pack/plugins/actions/server/builtin_action_types/case/schema.ts index f47686c911ff0..5a23eb89339e6 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/case/schema.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/case/schema.ts @@ -18,36 +18,18 @@ export const MapRecordSchema = schema.object({ actionType: MappingActionType, }); -export const CaseConfigurationSchema = schema.object({ +export const IncidentConfigurationSchema = schema.object({ mapping: schema.arrayOf(MapRecordSchema), }); -export const ExternalIncidentServiceConfiguration = { - apiUrl: schema.string(), - casesConfiguration: CaseConfigurationSchema, -}; - -export const ExternalIncidentServiceConfigurationSchema = schema.object( - ExternalIncidentServiceConfiguration -); - -export const ExternalIncidentServiceSecretConfiguration = { - password: schema.string(), - username: schema.string(), -}; - -export const ExternalIncidentServiceSecretConfigurationSchema = schema.object( - ExternalIncidentServiceSecretConfiguration -); - export const UserSchema = schema.object({ fullName: schema.nullable(schema.string()), username: schema.nullable(schema.string()), }); -const EntityInformation = { - createdAt: schema.string(), - createdBy: UserSchema, +export const EntityInformation = { + createdAt: schema.nullable(schema.string()), + createdBy: schema.nullable(UserSchema), updatedAt: schema.nullable(schema.string()), updatedBy: schema.nullable(UserSchema), }; @@ -59,40 +41,3 @@ export const CommentSchema = schema.object({ comment: schema.string(), ...EntityInformation, }); - -export const ExecutorSubActionSchema = schema.oneOf([ - schema.literal('getIncident'), - schema.literal('pushToService'), - schema.literal('handshake'), -]); - -export const ExecutorSubActionPushParamsSchema = schema.object({ - savedObjectId: schema.string(), - title: schema.string(), - description: schema.nullable(schema.string()), - comments: schema.nullable(schema.arrayOf(CommentSchema)), - externalId: schema.nullable(schema.string()), - ...EntityInformation, -}); - -export const ExecutorSubActionGetIncidentParamsSchema = schema.object({ - externalId: schema.string(), -}); - -// Reserved for future implementation -export const ExecutorSubActionHandshakeParamsSchema = schema.object({}); - -export const ExecutorParamsSchema = schema.oneOf([ - schema.object({ - subAction: schema.literal('getIncident'), - subActionParams: ExecutorSubActionGetIncidentParamsSchema, - }), - schema.object({ - subAction: schema.literal('handshake'), - subActionParams: ExecutorSubActionHandshakeParamsSchema, - }), - schema.object({ - subAction: schema.literal('pushToService'), - subActionParams: ExecutorSubActionPushParamsSchema, - }), -]); diff --git a/x-pack/plugins/actions/server/builtin_action_types/case/types.ts b/x-pack/plugins/actions/server/builtin_action_types/case/types.ts index 1030e3d9c5d8e..73d8297c638df 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/case/types.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/case/types.ts @@ -4,74 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ -// This will have to remain `any` until we can extend connectors with generics -// and circular dependencies eliminated. -/* eslint-disable @typescript-eslint/no-explicit-any */ - import { TypeOf } from '@kbn/config-schema'; -import { Logger } from '../../../../../../src/core/server'; - import { - ExternalIncidentServiceConfigurationSchema, - ExternalIncidentServiceSecretConfigurationSchema, - ExecutorParamsSchema, - CaseConfigurationSchema, + IncidentConfigurationSchema, MapRecordSchema, CommentSchema, - ExecutorSubActionPushParamsSchema, - ExecutorSubActionGetIncidentParamsSchema, - ExecutorSubActionHandshakeParamsSchema, + EntityInformationSchema, } from './schema'; -import { LicenseType } from '../../../../../legacy/common/constants'; - -export interface AnyParams { - [index: string]: string | number | object | undefined | null; -} - -export type ExternalIncidentServiceConfiguration = TypeOf< - typeof ExternalIncidentServiceConfigurationSchema ->; -export type ExternalIncidentServiceSecretConfiguration = TypeOf< - typeof ExternalIncidentServiceSecretConfigurationSchema ->; - -export type ExecutorParams = TypeOf; -export type ExecutorSubActionPushParams = TypeOf; -export type ExecutorSubActionGetIncidentParams = TypeOf< - typeof ExecutorSubActionGetIncidentParamsSchema ->; - -export type ExecutorSubActionHandshakeParams = TypeOf< - typeof ExecutorSubActionHandshakeParamsSchema ->; - -export type CaseConfiguration = TypeOf; +export type IncidentConfiguration = TypeOf; export type MapRecord = TypeOf; export type Comment = TypeOf; - -export interface ExternalServiceConfiguration { - id: string; - name: string; - minimumLicenseRequired: LicenseType; -} - -export interface ExternalServiceCredentials { - config: Record; - secrets: Record; -} - -export interface ExternalServiceValidation { - config: (configurationUtilities: any, configObject: any) => void; - secrets: (configurationUtilities: any, secrets: any) => void; -} - -export interface ExternalServiceIncidentResponse { - id: string; - title: string; - url: string; - pushedDate: string; -} +export type EntityInformation = TypeOf; export interface ExternalServiceCommentResponse { commentId: string; @@ -79,69 +23,6 @@ export interface ExternalServiceCommentResponse { externalCommentId?: string; } -export interface ExternalServiceParams { - [index: string]: any; -} - -export interface ExternalService { - getIncident: (id: string) => Promise; - createIncident: (params: ExternalServiceParams) => Promise; - updateIncident: (params: ExternalServiceParams) => Promise; - createComment: (params: ExternalServiceParams) => Promise; -} - -export interface PushToServiceApiParams extends ExecutorSubActionPushParams { - externalCase: Record; -} - -export interface ExternalServiceApiHandlerArgs { - externalService: ExternalService; - mapping: Map; -} - -export interface PushToServiceApiHandlerArgs extends ExternalServiceApiHandlerArgs { - params: PushToServiceApiParams; -} - -export interface GetIncidentApiHandlerArgs extends ExternalServiceApiHandlerArgs { - params: ExecutorSubActionGetIncidentParams; -} - -export interface HandshakeApiHandlerArgs extends ExternalServiceApiHandlerArgs { - params: ExecutorSubActionHandshakeParams; -} - -export interface PushToServiceResponse extends ExternalServiceIncidentResponse { - comments?: ExternalServiceCommentResponse[]; -} - -export interface ExternalServiceApi { - handshake: (args: HandshakeApiHandlerArgs) => Promise; - pushToService: (args: PushToServiceApiHandlerArgs) => Promise; - getIncident: (args: GetIncidentApiHandlerArgs) => Promise; -} - -export interface CreateExternalServiceBasicArgs { - api: ExternalServiceApi; - createExternalService: ( - credentials: ExternalServiceCredentials, - logger: Logger, - proxySettings?: any - ) => ExternalService; - logger: Logger; -} - -export interface CreateExternalServiceArgs extends CreateExternalServiceBasicArgs { - config: ExternalServiceConfiguration; - validate: ExternalServiceValidation; - validationSchema: { config: any; secrets: any }; -} - -export interface CreateActionTypeArgs { - configurationUtilities: any; - executor?: any; -} - export interface PipedField { key: string; value: string; @@ -149,16 +30,10 @@ export interface PipedField { pipes: string[]; } -export interface PrepareFieldsForTransformArgs { - externalCase: Record; - mapping: Map; - defaultPipes?: string[]; -} - -export interface TransformFieldsArgs { - params: PushToServiceApiParams; +export interface TransformFieldsArgs { + params: P; fields: PipedField[]; - currentIncident?: ExternalServiceParams; + currentIncident?: S; } export interface TransformerArgs { @@ -167,3 +42,13 @@ export interface TransformerArgs { user?: string; previousValue?: string; } + +export interface AnyParams { + [index: string]: string | number | object | undefined | null; +} + +export interface PrepareFieldsForTransformArgs { + externalCase: Record; + mapping: Map; + defaultPipes?: string[]; +} diff --git a/x-pack/plugins/actions/server/builtin_action_types/case/utils.test.ts b/x-pack/plugins/actions/server/builtin_action_types/case/utils.test.ts index 2e3cee3946d61..600e18eb5daff 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/case/utils.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/case/utils.test.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +/* eslint-disable @typescript-eslint/no-explicit-any */ + import { normalizeMapping, buildMap, @@ -14,7 +16,23 @@ import { } from './utils'; import { SUPPORTED_SOURCE_FIELDS } from './constants'; -import { Comment, MapRecord, PushToServiceApiParams } from './types'; +import { Comment, MapRecord } from './types'; + +interface Entity { + createdAt: string | null; + createdBy: { fullName: string; username: string } | null; + updatedAt: string | null; + updatedBy: { fullName: string; username: string } | null; +} + +interface PushToServiceApiParams extends Entity { + savedObjectId: string; + title: string; + description: string | null; + externalId: string | null; + externalObject: Record; + comments: Comment[]; +} const mapping: MapRecord[] = [ { source: 'title', target: 'short_description', actionType: 'overwrite' }, @@ -22,7 +40,6 @@ const mapping: MapRecord[] = [ { source: 'comments', target: 'comments', actionType: 'append' }, ]; -// eslint-disable-next-line @typescript-eslint/no-explicit-any const finalMapping: Map = new Map(); finalMapping.set('title', { @@ -61,7 +78,7 @@ const fullParams: PushToServiceApiParams = { updatedAt: null, updatedBy: null, externalId: null, - externalCase: { + externalObject: { short_description: 'a title', description: 'a description', }, @@ -154,7 +171,7 @@ describe('mapParams', () => { describe('prepareFieldsForTransformation', () => { test('prepare fields with defaults', () => { const res = prepareFieldsForTransformation({ - externalCase: fullParams.externalCase, + externalCase: fullParams.externalObject, mapping: finalMapping, }); expect(res).toEqual([ @@ -175,7 +192,7 @@ describe('prepareFieldsForTransformation', () => { test('prepare fields with default pipes', () => { const res = prepareFieldsForTransformation({ - externalCase: fullParams.externalCase, + externalCase: fullParams.externalObject, mapping: finalMapping, defaultPipes: ['myTestPipe'], }); @@ -199,11 +216,15 @@ describe('prepareFieldsForTransformation', () => { describe('transformFields', () => { test('transform fields for creation correctly', () => { const fields = prepareFieldsForTransformation({ - externalCase: fullParams.externalCase, + externalCase: fullParams.externalObject, mapping: finalMapping, }); - const res = transformFields({ + const res = transformFields< + PushToServiceApiParams, + {}, + { short_description: string; description: string } + >({ params: fullParams, fields, }); @@ -216,12 +237,16 @@ describe('transformFields', () => { test('transform fields for update correctly', () => { const fields = prepareFieldsForTransformation({ - externalCase: fullParams.externalCase, + externalCase: fullParams.externalObject, mapping: finalMapping, defaultPipes: ['informationUpdated'], }); - const res = transformFields({ + const res = transformFields< + PushToServiceApiParams, + {}, + { short_description: string; description: string } + >({ params: { ...fullParams, updatedAt: '2020-03-15T08:34:53.450Z', @@ -245,12 +270,16 @@ describe('transformFields', () => { test('add newline character to description', () => { const fields = prepareFieldsForTransformation({ - externalCase: fullParams.externalCase, + externalCase: fullParams.externalObject, mapping: finalMapping, defaultPipes: ['informationUpdated'], }); - const res = transformFields({ + const res = transformFields< + PushToServiceApiParams, + {}, + { short_description: string; description: string } + >({ params: fullParams, fields, currentIncident: { @@ -263,11 +292,15 @@ describe('transformFields', () => { test('append username if fullname is undefined when create', () => { const fields = prepareFieldsForTransformation({ - externalCase: fullParams.externalCase, + externalCase: fullParams.externalObject, mapping: finalMapping, }); - const res = transformFields({ + const res = transformFields< + PushToServiceApiParams, + {}, + { short_description: string; description: string } + >({ params: { ...fullParams, createdBy: { fullName: '', username: 'elastic' }, @@ -283,12 +316,16 @@ describe('transformFields', () => { test('append username if fullname is undefined when update', () => { const fields = prepareFieldsForTransformation({ - externalCase: fullParams.externalCase, + externalCase: fullParams.externalObject, mapping: finalMapping, defaultPipes: ['informationUpdated'], }); - const res = transformFields({ + const res = transformFields< + PushToServiceApiParams, + {}, + { short_description: string; description: string } + >({ params: { ...fullParams, updatedAt: '2020-03-15T08:34:53.450Z', diff --git a/x-pack/plugins/actions/server/builtin_action_types/case/utils.ts b/x-pack/plugins/actions/server/builtin_action_types/case/utils.ts index 701bbea14fde8..3d51f5e826279 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/case/utils.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/case/utils.ts @@ -4,30 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ -import { curry, flow, get } from 'lodash'; -import { schema } from '@kbn/config-schema'; - -import { ActionTypeExecutorOptions, ActionTypeExecutorResult, ActionType } from '../../types'; - -import { ExecutorParamsSchema } from './schema'; -import { - ExternalIncidentServiceConfiguration, - ExternalIncidentServiceSecretConfiguration, -} from './types'; +import { flow, get } from 'lodash'; import { - CreateExternalServiceArgs, - CreateActionTypeArgs, - ExecutorParams, MapRecord, - AnyParams, - CreateExternalServiceBasicArgs, - PrepareFieldsForTransformArgs, - PipedField, TransformFieldsArgs, Comment, - ExecutorSubActionPushParams, - PushToServiceResponse, + EntityInformation, + PipedField, + AnyParams, + PrepareFieldsForTransformArgs, } from './types'; import { transformers } from './transformers'; @@ -61,92 +47,6 @@ export const mapParams = (params: T, mapping: Map async ( - execOptions: ActionTypeExecutorOptions< - ExternalIncidentServiceConfiguration, - ExternalIncidentServiceSecretConfiguration, - ExecutorParams - > -): Promise> => { - const { actionId, config, params, secrets } = execOptions; - const { subAction, subActionParams } = params; - let data = {}; - - const res: ActionTypeExecutorResult = { - status: 'ok', - actionId, - }; - - const externalService = createExternalService( - { - config, - secrets, - }, - logger, - execOptions.proxySettings - ); - - if (!api[subAction]) { - throw new Error('[Action][ExternalService] Unsupported subAction type.'); - } - - if (subAction !== 'pushToService') { - throw new Error('[Action][ExternalService] subAction not implemented.'); - } - - if (subAction === 'pushToService') { - const pushToServiceParams = subActionParams as ExecutorSubActionPushParams; - const { comments, externalId, ...restParams } = pushToServiceParams; - - const mapping = buildMap(config.casesConfiguration.mapping); - const externalCase = mapParams( - restParams as ExecutorSubActionPushParams, - mapping - ); - - data = await api.pushToService({ - externalService, - mapping, - params: { ...pushToServiceParams, externalCase }, - }); - } - - return { - ...res, - data, - }; -}; - -export const createConnector = ({ - api, - config, - validate, - createExternalService, - validationSchema, - logger, -}: CreateExternalServiceArgs) => { - return ({ - configurationUtilities, - executor = createConnectorExecutor({ api, createExternalService, logger }), - }: CreateActionTypeArgs): ActionType => ({ - ...config, - validate: { - config: schema.object(validationSchema.config, { - validate: curry(validate.config)(configurationUtilities), - }), - secrets: schema.object(validationSchema.secrets, { - validate: curry(validate.secrets)(configurationUtilities), - }), - params: ExecutorParamsSchema, - }, - executor, - }); -}; - export const prepareFieldsForTransformation = ({ externalCase, mapping, @@ -165,11 +65,15 @@ export const prepareFieldsForTransformation = ({ }); }; -export const transformFields = ({ +export const transformFields = < + P extends EntityInformation, + S extends Record, + R extends {} +>({ params, fields, currentIncident, -}: TransformFieldsArgs): Record => { +}: TransformFieldsArgs): R => { return fields.reduce((prev, cur) => { const transform = flow(...cur.pipes.map((p) => transformers[p])); return { @@ -177,18 +81,11 @@ export const transformFields = ({ [cur.key]: transform({ value: cur.value, date: params.updatedAt ?? params.createdAt, - user: - (params.updatedBy != null - ? params.updatedBy.fullName - ? params.updatedBy.fullName - : params.updatedBy.username - : params.createdBy.fullName - ? params.createdBy.fullName - : params.createdBy.username) ?? '', + user: getEntity(params), previousValue: currentIncident ? currentIncident[cur.key] : '', }).value, }; - }, {}); + }, {} as R); }; export const transformComments = (comments: Comment[], pipes: string[]): Comment[] => { @@ -197,18 +94,18 @@ export const transformComments = (comments: Comment[], pipes: string[]): Comment comment: flow(...pipes.map((p) => transformers[p]))({ value: c.comment, date: c.updatedAt ?? c.createdAt, - user: - (c.updatedBy != null - ? c.updatedBy.fullName - ? c.updatedBy.fullName - : c.updatedBy.username - : c.createdBy.fullName - ? c.createdBy.fullName - : c.createdBy.username) ?? '', + user: getEntity(c), }).value, })); }; -export const getErrorMessage = (connector: string, msg: string) => { - return `[Action][${connector}]: ${msg}`; -}; +export const getEntity = (entity: EntityInformation): string => + (entity.updatedBy != null + ? entity.updatedBy.fullName + ? entity.updatedBy.fullName + : entity.updatedBy.username + : entity.createdBy != null + ? entity.createdBy.fullName + ? entity.createdBy.fullName + : entity.createdBy.username + : '') ?? ''; diff --git a/x-pack/plugins/actions/server/builtin_action_types/case/validators.ts b/x-pack/plugins/actions/server/builtin_action_types/case/validators.ts deleted file mode 100644 index 08e8a8be6a3e6..0000000000000 --- a/x-pack/plugins/actions/server/builtin_action_types/case/validators.ts +++ /dev/null @@ -1,35 +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 { isEmpty } from 'lodash'; - -import { ActionsConfigurationUtilities } from '../../actions_config'; -import { - ExternalIncidentServiceConfiguration, - ExternalIncidentServiceSecretConfiguration, -} from './types'; - -import * as i18n from './translations'; - -export const validateCommonConfig = ( - configurationUtilities: ActionsConfigurationUtilities, - configObject: ExternalIncidentServiceConfiguration -) => { - try { - if (isEmpty(configObject.casesConfiguration.mapping)) { - return i18n.MAPPING_EMPTY; - } - - configurationUtilities.ensureUriAllowed(configObject.apiUrl); - } catch (allowListError) { - return i18n.WHITE_LISTED_ERROR(allowListError.message); - } -}; - -export const validateCommonSecrets = ( - configurationUtilities: ActionsConfigurationUtilities, - secrets: ExternalIncidentServiceSecretConfiguration -) => {}; diff --git a/x-pack/plugins/actions/server/builtin_action_types/jira/api.ts b/x-pack/plugins/actions/server/builtin_action_types/jira/api.ts index da47a4bfb839b..a64eb7a2036ca 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/jira/api.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/jira/api.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { flow } from 'lodash'; import { ExternalServiceParams, PushToServiceApiHandlerArgs, @@ -15,14 +14,11 @@ import { GetFieldsByIssueTypeHandlerArgs, GetIssueTypesHandlerArgs, PushToServiceApiParams, + PushToServiceResponse, } from './types'; // TODO: to remove, need to support Case -import { transformers } from '../case/transformers'; -import { TransformFieldsArgs, Comment, EntityInformation } from '../case/common_types'; - -import { PushToServiceResponse } from './types'; -import { prepareFieldsForTransformation } from '../case/utils'; +import { prepareFieldsForTransformation, transformFields, transformComments } from '../case/utils'; const handshakeHandler = async ({ externalService, @@ -81,7 +77,7 @@ const pushToServiceHandler = async ({ defaultPipes, }); - incident = transformFields({ + incident = transformFields({ params, fields, currentIncident, @@ -132,47 +128,6 @@ const pushToServiceHandler = async ({ return res; }; -export const transformFields = ({ - params, - fields, - currentIncident, -}: TransformFieldsArgs): Incident => { - return fields.reduce((prev, cur) => { - const transform = flow(...cur.pipes.map((p) => transformers[p])); - return { - ...prev, - [cur.key]: transform({ - value: cur.value, - date: params.updatedAt ?? params.createdAt, - user: getEntity(params), - previousValue: currentIncident ? currentIncident[cur.key] : '', - }).value, - }; - }, {} as Incident); -}; - -export const transformComments = (comments: Comment[], pipes: string[]): Comment[] => { - return comments.map((c) => ({ - ...c, - comment: flow(...pipes.map((p) => transformers[p]))({ - value: c.comment, - date: c.updatedAt ?? c.createdAt, - user: getEntity(c), - }).value, - })); -}; - -export const getEntity = (entity: EntityInformation): string => - (entity.updatedBy != null - ? entity.updatedBy.fullName - ? entity.updatedBy.fullName - : entity.updatedBy.username - : entity.createdBy != null - ? entity.createdBy.fullName - ? entity.createdBy.fullName - : entity.createdBy.username - : '') ?? ''; - export const api: ExternalServiceApi = { handshake: handshakeHandler, pushToService: pushToServiceHandler, diff --git a/x-pack/plugins/actions/server/builtin_action_types/jira/mocks.ts b/x-pack/plugins/actions/server/builtin_action_types/jira/mocks.ts index e7841996fedef..53f8d43ebc2d8 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/jira/mocks.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/jira/mocks.ts @@ -6,7 +6,7 @@ import { ExternalService, PushToServiceApiParams, ExecutorSubActionPushParams } from './types'; -import { MapRecord } from '../case/common_types'; +import { MapRecord } from '../case/types'; const createMock = (): jest.Mocked => { const service = { diff --git a/x-pack/plugins/actions/server/builtin_action_types/jira/schema.ts b/x-pack/plugins/actions/server/builtin_action_types/jira/schema.ts index 07c8e22812b27..9fee465e72efc 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/jira/schema.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/jira/schema.ts @@ -5,11 +5,7 @@ */ import { schema } from '@kbn/config-schema'; -import { - CommentSchema, - EntityInformation, - IncidentConfigurationSchema, -} from '../case/common_schema'; +import { CommentSchema, EntityInformation, IncidentConfigurationSchema } from '../case/schema'; export const ExternalIncidentServiceConfiguration = { apiUrl: schema.string(), diff --git a/x-pack/plugins/actions/server/builtin_action_types/jira/types.ts b/x-pack/plugins/actions/server/builtin_action_types/jira/types.ts index 5e97f5309f8ee..6fe7c62976f22 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/jira/types.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/jira/types.ts @@ -19,8 +19,8 @@ import { ExecutorSubActionGetFieldsByIssueTypeParamsSchema, } from './schema'; import { ActionsConfigurationUtilities } from '../../actions_config'; -import { IncidentConfigurationSchema } from '../case/common_schema'; -import { Comment } from '../case/common_types'; +import { IncidentConfigurationSchema } from '../case/schema'; +import { Comment } from '../case/types'; import { Logger } from '../../../../../../src/core/server'; export type JiraPublicConfigurationType = TypeOf; diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/api.test.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/api.test.ts index 734f6be382629..e974fedd0775b 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/api.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/resilient/api.test.ts @@ -4,9 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import { api } from '../case/api'; +import { Logger } from '../../../../../../src/core/server'; +import { api } from './api'; import { externalServiceMock, mapping, apiParams } from './mocks'; -import { ExternalService } from '../case/types'; +import { ExternalService } from './types'; + +let mockedLogger: jest.Mocked; describe('api', () => { let externalService: jest.Mocked; @@ -23,7 +26,12 @@ describe('api', () => { describe('create incident', () => { test('it creates an incident', async () => { const params = { ...apiParams, externalId: null }; - const res = await api.pushToService({ externalService, mapping, params }); + const res = await api.pushToService({ + externalService, + mapping, + params, + logger: mockedLogger, + }); expect(res).toEqual({ id: '1', @@ -45,7 +53,12 @@ describe('api', () => { test('it creates an incident without comments', async () => { const params = { ...apiParams, externalId: null, comments: [] }; - const res = await api.pushToService({ externalService, mapping, params }); + const res = await api.pushToService({ + externalService, + mapping, + params, + logger: mockedLogger, + }); expect(res).toEqual({ id: '1', @@ -57,7 +70,7 @@ describe('api', () => { test('it calls createIncident correctly', async () => { const params = { ...apiParams, externalId: null }; - await api.pushToService({ externalService, mapping, params }); + await api.pushToService({ externalService, mapping, params, logger: mockedLogger }); expect(externalService.createIncident).toHaveBeenCalledWith({ incident: { @@ -71,7 +84,7 @@ describe('api', () => { test('it calls createComment correctly', async () => { const params = { ...apiParams, externalId: null }; - await api.pushToService({ externalService, mapping, params }); + await api.pushToService({ externalService, mapping, params, logger: mockedLogger }); expect(externalService.createComment).toHaveBeenCalledTimes(2); expect(externalService.createComment).toHaveBeenNthCalledWith(1, { incidentId: '1', @@ -89,7 +102,6 @@ describe('api', () => { username: 'elastic', }, }, - field: 'comments', }); expect(externalService.createComment).toHaveBeenNthCalledWith(2, { @@ -108,14 +120,18 @@ describe('api', () => { username: 'elastic', }, }, - field: 'comments', }); }); }); describe('update incident', () => { test('it updates an incident', async () => { - const res = await api.pushToService({ externalService, mapping, params: apiParams }); + const res = await api.pushToService({ + externalService, + mapping, + params: apiParams, + logger: mockedLogger, + }); expect(res).toEqual({ id: '1', @@ -137,7 +153,12 @@ describe('api', () => { test('it updates an incident without comments', async () => { const params = { ...apiParams, comments: [] }; - const res = await api.pushToService({ externalService, mapping, params }); + const res = await api.pushToService({ + externalService, + mapping, + params, + logger: mockedLogger, + }); expect(res).toEqual({ id: '1', @@ -149,7 +170,7 @@ describe('api', () => { test('it calls updateIncident correctly', async () => { const params = { ...apiParams }; - await api.pushToService({ externalService, mapping, params }); + await api.pushToService({ externalService, mapping, params, logger: mockedLogger }); expect(externalService.updateIncident).toHaveBeenCalledWith({ incidentId: 'incident-3', @@ -164,7 +185,7 @@ describe('api', () => { test('it calls createComment correctly', async () => { const params = { ...apiParams }; - await api.pushToService({ externalService, mapping, params }); + await api.pushToService({ externalService, mapping, params, logger: mockedLogger }); expect(externalService.createComment).toHaveBeenCalledTimes(2); expect(externalService.createComment).toHaveBeenNthCalledWith(1, { incidentId: '1', @@ -182,7 +203,6 @@ describe('api', () => { username: 'elastic', }, }, - field: 'comments', }); expect(externalService.createComment).toHaveBeenNthCalledWith(2, { @@ -201,11 +221,52 @@ describe('api', () => { username: 'elastic', }, }, - field: 'comments', }); }); }); + describe('incidentTypes', () => { + test('it returns the incident types correctly', async () => { + const res = await api.incidentTypes({ + externalService, + params: {}, + }); + expect(res).toEqual([ + { + id: 17, + name: 'Communication error (fax; email)', + }, + { + id: 1001, + name: 'Custom type', + }, + ]); + }); + }); + + describe('severity', () => { + test('it returns the severity correctly', async () => { + const res = await api.severity({ + externalService, + params: { id: '10006' }, + }); + expect(res).toEqual([ + { + id: 4, + name: 'Low', + }, + { + id: 5, + name: 'Medium', + }, + { + id: 6, + name: 'High', + }, + ]); + }); + }); + describe('mapping variations', () => { test('overwrite & append', async () => { mapping.set('title', { @@ -228,7 +289,12 @@ describe('api', () => { actionType: 'overwrite', }); - await api.pushToService({ externalService, mapping, params: apiParams }); + await api.pushToService({ + externalService, + mapping, + params: apiParams, + logger: mockedLogger, + }); expect(externalService.updateIncident).toHaveBeenCalledWith({ incidentId: 'incident-3', incident: { @@ -260,7 +326,12 @@ describe('api', () => { actionType: 'nothing', }); - await api.pushToService({ externalService, mapping, params: apiParams }); + await api.pushToService({ + externalService, + mapping, + params: apiParams, + logger: mockedLogger, + }); expect(externalService.updateIncident).toHaveBeenCalledWith({ incidentId: 'incident-3', incident: { @@ -291,7 +362,12 @@ describe('api', () => { actionType: 'append', }); - await api.pushToService({ externalService, mapping, params: apiParams }); + await api.pushToService({ + externalService, + mapping, + params: apiParams, + logger: mockedLogger, + }); expect(externalService.updateIncident).toHaveBeenCalledWith({ incidentId: 'incident-3', incident: { @@ -324,7 +400,12 @@ describe('api', () => { actionType: 'nothing', }); - await api.pushToService({ externalService, mapping, params: apiParams }); + await api.pushToService({ + externalService, + mapping, + params: apiParams, + logger: mockedLogger, + }); expect(externalService.updateIncident).toHaveBeenCalledWith({ incidentId: 'incident-3', incident: {}, @@ -352,7 +433,12 @@ describe('api', () => { actionType: 'overwrite', }); - await api.pushToService({ externalService, mapping, params: apiParams }); + await api.pushToService({ + externalService, + mapping, + params: apiParams, + logger: mockedLogger, + }); expect(externalService.updateIncident).toHaveBeenCalledWith({ incidentId: 'incident-3', incident: { @@ -382,7 +468,12 @@ describe('api', () => { actionType: 'overwrite', }); - await api.pushToService({ externalService, mapping, params: apiParams }); + await api.pushToService({ + externalService, + mapping, + params: apiParams, + logger: mockedLogger, + }); expect(externalService.updateIncident).toHaveBeenCalledWith({ incidentId: 'incident-3', incident: { @@ -414,7 +505,12 @@ describe('api', () => { actionType: 'nothing', }); - await api.pushToService({ externalService, mapping, params: apiParams }); + await api.pushToService({ + externalService, + mapping, + params: apiParams, + logger: mockedLogger, + }); expect(externalService.updateIncident).toHaveBeenCalledWith({ incidentId: 'incident-3', incident: { @@ -445,7 +541,12 @@ describe('api', () => { actionType: 'append', }); - await api.pushToService({ externalService, mapping, params: apiParams }); + await api.pushToService({ + externalService, + mapping, + params: apiParams, + logger: mockedLogger, + }); expect(externalService.updateIncident).toHaveBeenCalledWith({ incidentId: 'incident-3', incident: { @@ -478,7 +579,12 @@ describe('api', () => { actionType: 'append', }); - await api.pushToService({ externalService, mapping, params: apiParams }); + await api.pushToService({ + externalService, + mapping, + params: apiParams, + logger: mockedLogger, + }); expect(externalService.updateIncident).toHaveBeenCalledWith({ incidentId: 'incident-3', incident: { @@ -509,7 +615,12 @@ describe('api', () => { actionType: 'overwrite', }); - await api.pushToService({ externalService, mapping, params: apiParams }); + await api.pushToService({ + externalService, + mapping, + params: apiParams, + logger: mockedLogger, + }); expect(externalService.createComment).not.toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/api.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/api.ts index 3db66e5884af4..af3984bf5f0fa 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/api.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/resilient/api.ts @@ -4,4 +4,129 @@ * you may not use this file except in compliance with the Elastic License. */ -export { api } from '../case/api'; +import { + ExternalServiceParams, + PushToServiceApiHandlerArgs, + HandshakeApiHandlerArgs, + GetIncidentApiHandlerArgs, + ExternalServiceApi, + Incident, + GetIncidentTypesHandlerArgs, + GetSeverityHandlerArgs, + PushToServiceApiParams, + PushToServiceResponse, +} from './types'; + +// TODO: to remove, need to support Case +import { transformFields, prepareFieldsForTransformation, transformComments } from '../case/utils'; + +const handshakeHandler = async ({ + externalService, + mapping, + params, +}: HandshakeApiHandlerArgs) => {}; + +const getIncidentHandler = async ({ + externalService, + mapping, + params, +}: GetIncidentApiHandlerArgs) => {}; + +const getIncidentTypesHandler = async ({ externalService }: GetIncidentTypesHandlerArgs) => { + const res = await externalService.getIncidentTypes(); + return res; +}; + +const getSeverityHandler = async ({ externalService }: GetSeverityHandlerArgs) => { + const res = await externalService.getSeverity(); + return res; +}; + +const pushToServiceHandler = async ({ + externalService, + mapping, + params, + logger, +}: PushToServiceApiHandlerArgs): Promise => { + const { externalId, comments } = params; + const updateIncident = externalId ? true : false; + const defaultPipes = updateIncident ? ['informationUpdated'] : ['informationCreated']; + let currentIncident: ExternalServiceParams | undefined; + let res: PushToServiceResponse; + + if (externalId) { + try { + currentIncident = await externalService.getIncident(externalId); + } catch (ex) { + logger.debug( + `Retrieving Incident by id ${externalId} from IBM Resilient was failed with exception: ${ex}` + ); + } + } + + let incident: Incident; + // TODO: should be removed later but currently keep it for the Case implementation support + if (mapping) { + const fields = prepareFieldsForTransformation({ + externalCase: params.externalObject, + mapping, + defaultPipes, + }); + + incident = transformFields({ + params, + fields, + currentIncident, + }); + } else { + const { title, description, incidentTypes, severityCode } = params; + incident = { name: title, description, incidentTypes, severityCode }; + } + + if (externalId != null) { + res = await externalService.updateIncident({ + incidentId: externalId, + incident, + }); + } else { + res = await externalService.createIncident({ + incident: { + ...incident, + }, + }); + } + + if (comments && Array.isArray(comments) && comments.length > 0) { + if (mapping && mapping.get('comments')?.actionType === 'nothing') { + return res; + } + const commentsTransformed = mapping + ? transformComments(comments, ['informationAdded']) + : comments; + + res.comments = []; + for (const currentComment of commentsTransformed) { + const comment = await externalService.createComment({ + incidentId: res.id, + comment: currentComment, + }); + res.comments = [ + ...(res.comments ?? []), + { + commentId: comment.commentId, + pushedDate: comment.pushedDate, + }, + ]; + } + } + + return res; +}; + +export const api: ExternalServiceApi = { + handshake: handshakeHandler, + pushToService: pushToServiceHandler, + getIncident: getIncidentHandler, + incidentTypes: getIncidentTypesHandler, + severity: getSeverityHandler, +}; diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/config.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/config.ts deleted file mode 100644 index 4ce9417bfa9a1..0000000000000 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/config.ts +++ /dev/null @@ -1,14 +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 { ExternalServiceConfiguration } from '../case/types'; -import * as i18n from './translations'; - -export const config: ExternalServiceConfiguration = { - id: '.resilient', - name: i18n.NAME, - minimumLicenseRequired: 'platinum', -}; diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/index.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/index.ts index 1e9cb15589702..53285a2a350af 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/index.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/resilient/index.ts @@ -4,33 +4,139 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Logger } from '../../../../../../src/core/server'; -import { createConnector } from '../case/utils'; +import { curry } from 'lodash'; +import { schema } from '@kbn/config-schema'; -import { api } from './api'; -import { config } from './config'; import { validate } from './validators'; -import { createExternalService } from './service'; -import { ResilientSecretConfiguration, ResilientPublicConfiguration } from './schema'; +import { + ExternalIncidentServiceConfiguration, + ExternalIncidentServiceSecretConfiguration, + ExecutorParamsSchema, +} from './schema'; import { ActionsConfigurationUtilities } from '../../actions_config'; -import { ActionType } from '../../types'; +import { ActionType, ActionTypeExecutorOptions, ActionTypeExecutorResult } from '../../types'; +import { createExternalService } from './service'; +import { api } from './api'; +import { + ExecutorParams, + ExecutorSubActionPushParams, + ResilientPublicConfigurationType, + ResilientSecretConfigurationType, + ResilientExecutorResultData, + ExecutorSubActionGetIncidentTypesParams, + ExecutorSubActionGetSeverityParams, +} from './types'; +import * as i18n from './translations'; +import { Logger } from '../../../../../../src/core/server'; -export function getActionType({ - logger, - configurationUtilities, -}: { +// TODO: to remove, need to support Case +import { buildMap, mapParams } from '../case/utils'; + +interface GetActionTypeParams { logger: Logger; configurationUtilities: ActionsConfigurationUtilities; -}): ActionType { - return createConnector({ - api, - config, - validate, - createExternalService, - validationSchema: { - config: ResilientPublicConfiguration, - secrets: ResilientSecretConfiguration, +} + +const supportedSubActions: string[] = ['pushToService', 'incidentTypes', 'severity']; + +// action type definition +export function getActionType( + params: GetActionTypeParams +): ActionType< + ResilientPublicConfigurationType, + ResilientSecretConfigurationType, + ExecutorParams, + ResilientExecutorResultData | {} +> { + const { logger, configurationUtilities } = params; + return { + id: '.resilient', + minimumLicenseRequired: 'platinum', + name: i18n.NAME, + validate: { + config: schema.object(ExternalIncidentServiceConfiguration, { + validate: curry(validate.config)(configurationUtilities), + }), + secrets: schema.object(ExternalIncidentServiceSecretConfiguration, { + validate: curry(validate.secrets)(configurationUtilities), + }), + params: ExecutorParamsSchema, + }, + executor: curry(executor)({ logger }), + }; +} + +// action executor +async function executor( + { logger }: { logger: Logger }, + execOptions: ActionTypeExecutorOptions< + ResilientPublicConfigurationType, + ResilientSecretConfigurationType, + ExecutorParams + > +): Promise> { + const { actionId, config, params, secrets } = execOptions; + const { subAction, subActionParams } = params as ExecutorParams; + let data: ResilientExecutorResultData | null = null; + + const externalService = createExternalService( + { + config, + secrets, }, logger, - })({ configurationUtilities }); + execOptions.proxySettings + ); + + if (!api[subAction]) { + const errorMessage = `[Action][ExternalService] Unsupported subAction type ${subAction}.`; + logger.error(errorMessage); + throw new Error(errorMessage); + } + + if (!supportedSubActions.includes(subAction)) { + const errorMessage = `[Action][ExternalService] subAction ${subAction} not implemented.`; + logger.error(errorMessage); + throw new Error(errorMessage); + } + + if (subAction === 'pushToService') { + const pushToServiceParams = subActionParams as ExecutorSubActionPushParams; + + const { comments, externalId, ...restParams } = pushToServiceParams; + const mapping = config.incidentConfiguration + ? buildMap(config.incidentConfiguration.mapping) + : null; + const externalObject = + config.incidentConfiguration && mapping + ? mapParams(restParams as ExecutorSubActionPushParams, mapping) + : {}; + + data = await api.pushToService({ + externalService, + mapping, + params: { ...pushToServiceParams, externalObject }, + logger, + }); + + logger.debug(`response push to service for incident id: ${data.id}`); + } + + if (subAction === 'incidentTypes') { + const incidentTypesParams = subActionParams as ExecutorSubActionGetIncidentTypesParams; + data = await api.incidentTypes({ + externalService, + params: incidentTypesParams, + }); + } + + if (subAction === 'severity') { + const severityParams = subActionParams as ExecutorSubActionGetSeverityParams; + data = await api.severity({ + externalService, + params: severityParams, + }); + } + + return { status: 'ok', data: data ?? {}, actionId }; } diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/mocks.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/mocks.ts index bba9c58bf28c9..2e841728159a3 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/mocks.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/resilient/mocks.ts @@ -4,12 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - ExternalService, - PushToServiceApiParams, - ExecutorSubActionPushParams, - MapRecord, -} from '../case/types'; +import { ExternalService, PushToServiceApiParams, ExecutorSubActionPushParams } from './types'; + +import { MapRecord } from '../case/types'; const createMock = (): jest.Mocked => { const service = { @@ -40,6 +37,25 @@ const createMock = (): jest.Mocked => { }) ), createComment: jest.fn(), + findIncidents: jest.fn(), + getIncidentTypes: jest.fn().mockImplementation(() => [ + { id: 17, name: 'Communication error (fax; email)' }, + { id: 1001, name: 'Custom type' }, + ]), + getSeverity: jest.fn().mockImplementation(() => [ + { + id: 4, + name: 'Low', + }, + { + id: 5, + name: 'Medium', + }, + { + id: 6, + name: 'High', + }, + ]), }; service.createComment.mockImplementationOnce(() => @@ -96,6 +112,8 @@ const executorParams: ExecutorSubActionPushParams = { updatedBy: { fullName: 'Elastic User', username: 'elastic' }, title: 'Incident title', description: 'Incident description', + incidentTypes: [1001], + severityCode: 6, comments: [ { commentId: 'case-comment-1', @@ -118,7 +136,58 @@ const executorParams: ExecutorSubActionPushParams = { const apiParams: PushToServiceApiParams = { ...executorParams, - externalCase: { name: 'Incident title', description: 'Incident description' }, + externalObject: { name: 'Incident title', description: 'Incident description' }, }; -export { externalServiceMock, mapping, executorParams, apiParams }; +const incidentTypes = [ + { + value: 17, + label: 'Communication error (fax; email)', + enabled: true, + properties: null, + uuid: '4a8d22f7-d89e-4403-85c7-2bafe3b7f2ae', + hidden: false, + default: false, + }, + { + value: 1001, + label: 'Custom type', + enabled: true, + properties: null, + uuid: '3b51c8c2-9758-48f8-b013-bd141f1d2ec9', + hidden: false, + default: false, + }, +]; + +const severity = [ + { + value: 4, + label: 'Low', + enabled: true, + properties: null, + uuid: '97cae239-963d-4e36-be34-07e47ef2cc86', + hidden: false, + default: true, + }, + { + value: 5, + label: 'Medium', + enabled: true, + properties: null, + uuid: 'c2c354c9-6d1e-4a48-82e5-bd5dc5068339', + hidden: false, + default: false, + }, + { + value: 6, + label: 'High', + enabled: true, + properties: null, + uuid: '93e5c99c-563b-48b9-80a3-9572307622d8', + hidden: false, + default: false, + }, +]; + +export { externalServiceMock, mapping, executorParams, apiParams, incidentTypes, severity }; diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/schema.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/schema.ts index c13de2b27e2b9..151f703dcc07e 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/schema.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/resilient/schema.ts @@ -5,18 +5,77 @@ */ import { schema } from '@kbn/config-schema'; -import { ExternalIncidentServiceConfiguration } from '../case/schema'; +import { CommentSchema, EntityInformation, IncidentConfigurationSchema } from '../case/schema'; -export const ResilientPublicConfiguration = { +export const ExternalIncidentServiceConfiguration = { + apiUrl: schema.string(), orgId: schema.string(), - ...ExternalIncidentServiceConfiguration, + // TODO: to remove - set it optional for the current stage to support Case implementation + incidentConfiguration: schema.nullable(IncidentConfigurationSchema), + isCaseOwned: schema.nullable(schema.boolean()), }; -export const ResilientPublicConfigurationSchema = schema.object(ResilientPublicConfiguration); +export const ExternalIncidentServiceConfigurationSchema = schema.object( + ExternalIncidentServiceConfiguration +); -export const ResilientSecretConfiguration = { +export const ExternalIncidentServiceSecretConfiguration = { apiKeyId: schema.string(), apiKeySecret: schema.string(), }; -export const ResilientSecretConfigurationSchema = schema.object(ResilientSecretConfiguration); +export const ExternalIncidentServiceSecretConfigurationSchema = schema.object( + ExternalIncidentServiceSecretConfiguration +); + +export const ExecutorSubActionSchema = schema.oneOf([ + schema.literal('getIncident'), + schema.literal('pushToService'), + schema.literal('handshake'), + schema.literal('incidentTypes'), + schema.literal('severity'), +]); + +export const ExecutorSubActionPushParamsSchema = schema.object({ + savedObjectId: schema.string(), + title: schema.string(), + description: schema.nullable(schema.string()), + externalId: schema.nullable(schema.string()), + incidentTypes: schema.nullable(schema.arrayOf(schema.number())), + severityCode: schema.nullable(schema.number()), + // TODO: remove later - need for support Case push multiple comments + comments: schema.nullable(schema.arrayOf(CommentSchema)), + ...EntityInformation, +}); + +export const ExecutorSubActionGetIncidentParamsSchema = schema.object({ + externalId: schema.string(), +}); + +// Reserved for future implementation +export const ExecutorSubActionHandshakeParamsSchema = schema.object({}); +export const ExecutorSubActionGetIncidentTypesParamsSchema = schema.object({}); +export const ExecutorSubActionGetSeverityParamsSchema = schema.object({}); + +export const ExecutorParamsSchema = schema.oneOf([ + schema.object({ + subAction: schema.literal('getIncident'), + subActionParams: ExecutorSubActionGetIncidentParamsSchema, + }), + schema.object({ + subAction: schema.literal('handshake'), + subActionParams: ExecutorSubActionHandshakeParamsSchema, + }), + schema.object({ + subAction: schema.literal('pushToService'), + subActionParams: ExecutorSubActionPushParamsSchema, + }), + schema.object({ + subAction: schema.literal('incidentTypes'), + subActionParams: ExecutorSubActionGetIncidentTypesParamsSchema, + }), + schema.object({ + subAction: schema.literal('severity'), + subActionParams: ExecutorSubActionGetSeverityParamsSchema, + }), +]); diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/service.test.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/service.test.ts index a9271671f68b9..86ea352625a5b 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/service.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/resilient/service.test.ts @@ -8,9 +8,11 @@ import axios from 'axios'; import { createExternalService, getValueTextContent, formatUpdateRequest } from './service'; import * as utils from '../lib/axios_utils'; -import { ExternalService } from '../case/types'; +import { ExternalService } from './types'; import { Logger } from '../../../../../../src/core/server'; import { loggingSystemMock } from '../../../../../../src/core/server/mocks'; +import { incidentTypes, severity } from './mocks'; + const logger = loggingSystemMock.create().get() as jest.Mocked; jest.mock('axios'); @@ -41,6 +43,8 @@ const mockIncidentUpdate = (withUpdateError = false) => { format: 'html', content: 'description', }, + incident_type_ids: [1001, 16, 12], + severity_code: 6, }, })); @@ -246,7 +250,12 @@ describe('IBM Resilient service', () => { })); const res = await service.createIncident({ - incident: { name: 'title', description: 'desc' }, + incident: { + name: 'title', + description: 'desc', + incidentTypes: [1001], + severityCode: 6, + }, }); expect(res).toEqual({ @@ -269,12 +278,18 @@ describe('IBM Resilient service', () => { })); await service.createIncident({ - incident: { name: 'title', description: 'desc' }, + incident: { + name: 'title', + description: 'desc', + incidentTypes: [1001], + severityCode: 6, + }, }); expect(requestMock).toHaveBeenCalledWith({ axios, - url: 'https://resilient.elastic.co/rest/orgs/201/incidents', + url: + 'https://resilient.elastic.co/rest/orgs/201/incidents?text_content_output_format=objects_convert', logger, method: 'post', data: { @@ -284,6 +299,8 @@ describe('IBM Resilient service', () => { content: 'desc', }, discovered_date: TIMESTAMP, + incident_type_ids: [{ id: 1001 }], + severity_code: { id: 6 }, }, }); }); @@ -295,7 +312,12 @@ describe('IBM Resilient service', () => { expect( service.createIncident({ - incident: { name: 'title', description: 'desc' }, + incident: { + name: 'title', + description: 'desc', + incidentTypes: [1001], + severityCode: 6, + }, }) ).rejects.toThrow( '[Action][IBM Resilient]: Unable to create incident. Error: An error has occurred' @@ -308,7 +330,12 @@ describe('IBM Resilient service', () => { mockIncidentUpdate(); const res = await service.updateIncident({ incidentId: '1', - incident: { name: 'title_updated', description: 'desc_updated' }, + incident: { + name: 'title', + description: 'desc', + incidentTypes: [1001], + severityCode: 6, + }, }); expect(res).toEqual({ @@ -324,7 +351,12 @@ describe('IBM Resilient service', () => { await service.updateIncident({ incidentId: '1', - incident: { name: 'title_updated', description: 'desc_updated' }, + incident: { + name: 'title_updated', + description: 'desc_updated', + incidentTypes: [1001], + severityCode: 5, + }, }); // Incident update makes three calls to the API. @@ -356,6 +388,28 @@ describe('IBM Resilient service', () => { }, }, }, + { + field: { + name: 'incident_type_ids', + }, + old_value: { + ids: [1001, 16, 12], + }, + new_value: { + ids: [1001], + }, + }, + { + field: { + name: 'severity_code', + }, + old_value: { + id: 6, + }, + new_value: { + id: 5, + }, + }, ], }, }); @@ -367,7 +421,12 @@ describe('IBM Resilient service', () => { expect( service.updateIncident({ incidentId: '1', - incident: { name: 'title', description: 'desc' }, + incident: { + name: 'title', + description: 'desc', + incidentTypes: [1001], + severityCode: 5, + }, }) ).rejects.toThrow( '[Action][IBM Resilient]: Unable to update incident with id 1. Error: An error has occurred' @@ -386,8 +445,14 @@ describe('IBM Resilient service', () => { const res = await service.createComment({ incidentId: '1', - comment: { comment: 'comment', commentId: 'comment-1' }, - field: 'comments', + comment: { + comment: 'comment', + commentId: 'comment-1', + createdBy: null, + createdAt: null, + updatedAt: null, + updatedBy: null, + }, }); expect(res).toEqual({ @@ -407,8 +472,14 @@ describe('IBM Resilient service', () => { await service.createComment({ incidentId: '1', - comment: { comment: 'comment', commentId: 'comment-1' }, - field: 'my_field', + comment: { + comment: 'comment', + commentId: 'comment-1', + createdBy: null, + createdAt: null, + updatedAt: null, + updatedBy: null, + }, }); expect(requestMock).toHaveBeenCalledWith({ @@ -434,12 +505,82 @@ describe('IBM Resilient service', () => { expect( service.createComment({ incidentId: '1', - comment: { comment: 'comment', commentId: 'comment-1' }, - field: 'comments', + comment: { + comment: 'comment', + commentId: 'comment-1', + createdBy: null, + createdAt: null, + updatedAt: null, + updatedBy: null, + }, }) ).rejects.toThrow( '[Action][IBM Resilient]: Unable to create comment at incident with id 1. Error: An error has occurred' ); }); }); + + describe('getIncidentTypes', () => { + test('it creates the incident correctly', async () => { + requestMock.mockImplementation(() => ({ + data: { + values: incidentTypes, + }, + })); + + const res = await service.getIncidentTypes(); + + expect(res).toEqual([ + { id: 17, name: 'Communication error (fax; email)' }, + { id: 1001, name: 'Custom type' }, + ]); + }); + + test('it should throw an error', async () => { + requestMock.mockImplementation(() => { + throw new Error('An error has occurred'); + }); + + expect(service.getIncidentTypes()).rejects.toThrow( + '[Action][IBM Resilient]: Unable to get incident types. Error: An error has occurred.' + ); + }); + }); + + describe('getSeverity', () => { + test('it creates the incident correctly', async () => { + requestMock.mockImplementation(() => ({ + data: { + values: severity, + }, + })); + + const res = await service.getSeverity(); + + expect(res).toEqual([ + { + id: 4, + name: 'Low', + }, + { + id: 5, + name: 'Medium', + }, + { + id: 6, + name: 'High', + }, + ]); + }); + + test('it should throw an error', async () => { + requestMock.mockImplementation(() => { + throw new Error('An error has occurred'); + }); + + expect(service.getIncidentTypes()).rejects.toThrow( + '[Action][IBM Resilient]: Unable to get incident types. Error: An error has occurred.' + ); + }); + }); }); diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/service.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/service.ts index b2150081f2c89..4bf1453641e42 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/service.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/resilient/service.ts @@ -5,44 +5,56 @@ */ import axios from 'axios'; +import { omitBy, isNil } from 'lodash/fp'; import { Logger } from '../../../../../../src/core/server'; -import { ExternalServiceCredentials, ExternalService, ExternalServiceParams } from '../case/types'; import { + ExternalServiceCredentials, + ExternalService, + ExternalServiceParams, + CreateCommentParams, + UpdateIncidentParams, + CreateIncidentParams, + CreateIncidentData, ResilientPublicConfigurationType, ResilientSecretConfigurationType, - CreateIncidentRequest, UpdateIncidentRequest, - CreateCommentRequest, - UpdateFieldText, - UpdateFieldTextArea, + GetValueTextContentResponse, } from './types'; import * as i18n from './translations'; import { getErrorMessage, request } from '../lib/axios_utils'; import { ProxySettings } from '../../types'; -const BASE_URL = `rest`; -const INCIDENT_URL = `incidents`; -const COMMENT_URL = `comments`; - const VIEW_INCIDENT_URL = `#incidents`; export const getValueTextContent = ( field: string, - value: string -): UpdateFieldText | UpdateFieldTextArea => { + value: string | number | number[] +): GetValueTextContentResponse => { if (field === 'description') { return { textarea: { format: 'html', - content: value, + content: value as string, }, }; } + if (field === 'incidentTypes') { + return { + ids: value as number[], + }; + } + + if (field === 'severityCode') { + return { + id: value as number, + }; + } + return { - text: value, + text: value as string, }; }; @@ -51,11 +63,30 @@ export const formatUpdateRequest = ({ newIncident, }: ExternalServiceParams): UpdateIncidentRequest => { return { - changes: Object.keys(newIncident).map((key) => ({ - field: { name: key }, - old_value: getValueTextContent(key, oldIncident[key]), - new_value: getValueTextContent(key, newIncident[key]), - })), + changes: Object.keys(newIncident as Record).map((key) => { + let name = key; + + if (key === 'incidentTypes') { + name = 'incident_type_ids'; + } + + if (key === 'severityCode') { + name = 'severity_code'; + } + + return { + field: { name }, + // TODO: Fix ugly casting + old_value: getValueTextContent( + key, + (oldIncident as Record)[name] as string + ), + new_value: getValueTextContent( + key, + (newIncident as Record)[key] as string + ), + }; + }), }; }; @@ -72,8 +103,12 @@ export const createExternalService = ( } const urlWithoutTrailingSlash = url.endsWith('/') ? url.slice(0, -1) : url; - const incidentUrl = `${urlWithoutTrailingSlash}/${BASE_URL}/orgs/${orgId}/${INCIDENT_URL}`; - const commentUrl = `${incidentUrl}/{inc_id}/${COMMENT_URL}`; + const orgUrl = `${urlWithoutTrailingSlash}/rest/orgs/${orgId}`; + const incidentUrl = `${orgUrl}/incidents`; + const commentUrl = `${incidentUrl}/{inc_id}/comments`; + const incidentFieldsUrl = `${orgUrl}/types/incident/fields`; + const incidentTypesUrl = `${incidentFieldsUrl}/incident_type_ids`; + const severityUrl = `${incidentFieldsUrl}/severity_code`; const axiosInstance = axios.create({ auth: { username: apiKeyId, password: apiKeySecret }, }); @@ -101,26 +136,48 @@ export const createExternalService = ( return { ...res.data, description: res.data.description?.content ?? '' }; } catch (error) { throw new Error( - getErrorMessage(i18n.NAME, `Unable to get incident with id ${id}. Error: ${error.message}`) + getErrorMessage(i18n.NAME, `Unable to get incident with id ${id}. Error: ${error.message}.`) ); } }; - const createIncident = async ({ incident }: ExternalServiceParams) => { + const createIncident = async ({ incident }: CreateIncidentParams) => { + let data: CreateIncidentData = { + name: incident.name, + discovered_date: Date.now(), + }; + + if (incident.description) { + data = { + ...data, + description: { + format: 'html', + content: incident.description ?? '', + }, + }; + } + + if (incident.incidentTypes) { + data = { + ...data, + incident_type_ids: incident.incidentTypes.map((id) => ({ id })), + }; + } + + if (incident.severityCode) { + data = { + ...data, + severity_code: { id: incident.severityCode }, + }; + } + try { - const res = await request({ + const res = await request({ axios: axiosInstance, - url: `${incidentUrl}`, + url: `${incidentUrl}?text_content_output_format=objects_convert`, method: 'post', logger, - data: { - ...incident, - description: { - format: 'html', - content: incident.description ?? '', - }, - discovered_date: Date.now(), - }, + data, proxySettings, }); @@ -132,17 +189,20 @@ export const createExternalService = ( }; } catch (error) { throw new Error( - getErrorMessage(i18n.NAME, `Unable to create incident. Error: ${error.message}`) + getErrorMessage(i18n.NAME, `Unable to create incident. Error: ${error.message}.`) ); } }; - const updateIncident = async ({ incidentId, incident }: ExternalServiceParams) => { + const updateIncident = async ({ incidentId, incident }: UpdateIncidentParams) => { try { const latestIncident = await getIncident(incidentId); - const data = formatUpdateRequest({ oldIncident: latestIncident, newIncident: incident }); - const res = await request({ + // Remove null or undefined values. Allowing null values sets the field in IBM Resilient to empty. + const newIncident = omitBy(isNil, incident); + const data = formatUpdateRequest({ oldIncident: latestIncident, newIncident }); + + const res = await request({ axios: axiosInstance, method: 'patch', url: `${incidentUrl}/${incidentId}`, @@ -173,9 +233,9 @@ export const createExternalService = ( } }; - const createComment = async ({ incidentId, comment, field }: ExternalServiceParams) => { + const createComment = async ({ incidentId, comment }: CreateCommentParams) => { try { - const res = await request({ + const res = await request({ axios: axiosInstance, method: 'post', url: getCommentsURL(incidentId), @@ -193,16 +253,62 @@ export const createExternalService = ( throw new Error( getErrorMessage( i18n.NAME, - `Unable to create comment at incident with id ${incidentId}. Error: ${error.message}` + `Unable to create comment at incident with id ${incidentId}. Error: ${error.message}.` ) ); } }; + const getIncidentTypes = async () => { + try { + const res = await request({ + axios: axiosInstance, + method: 'get', + url: incidentTypesUrl, + logger, + proxySettings, + }); + + const incidentTypes = res.data?.values ?? []; + return incidentTypes.map((type: { value: string; label: string }) => ({ + id: type.value, + name: type.label, + })); + } catch (error) { + throw new Error( + getErrorMessage(i18n.NAME, `Unable to get incident types. Error: ${error.message}.`) + ); + } + }; + + const getSeverity = async () => { + try { + const res = await request({ + axios: axiosInstance, + method: 'get', + url: severityUrl, + logger, + proxySettings, + }); + + const incidentTypes = res.data?.values ?? []; + return incidentTypes.map((type: { value: string; label: string }) => ({ + id: type.value, + name: type.label, + })); + } catch (error) { + throw new Error( + getErrorMessage(i18n.NAME, `Unable to get severity. Error: ${error.message}.`) + ); + } + }; + return { getIncident, createIncident, updateIncident, createComment, + getIncidentTypes, + getSeverity, }; }; diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/translations.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/translations.ts index d952838d5a2b3..8c6ce9902da81 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/translations.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/resilient/translations.ts @@ -9,3 +9,19 @@ import { i18n } from '@kbn/i18n'; export const NAME = i18n.translate('xpack.actions.builtin.case.resilientTitle', { defaultMessage: 'IBM Resilient', }); + +export const ALLOWED_HOSTS_ERROR = (message: string) => + i18n.translate('xpack.actions.builtin.configuration.apiAllowedHostsError', { + defaultMessage: 'error configuring connector action: {message}', + values: { + message, + }, + }); + +// TODO: remove when Case mappings will be removed +export const MAPPING_EMPTY = i18n.translate( + 'xpack.actions.builtin.servicenow.configuration.emptyMapping', + { + defaultMessage: '[incidentConfiguration.mapping]: expected non-empty but got empty', + } +); diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/types.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/types.ts index 6869e2ff3a105..ed622ee473b65 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/types.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/resilient/types.ts @@ -4,29 +4,175 @@ * you may not use this file except in compliance with the Elastic License. */ +/* eslint-disable @typescript-eslint/no-explicit-any */ + import { TypeOf } from '@kbn/config-schema'; -import { ResilientPublicConfigurationSchema, ResilientSecretConfigurationSchema } from './schema'; +import { + ExternalIncidentServiceConfigurationSchema, + ExternalIncidentServiceSecretConfigurationSchema, + ExecutorParamsSchema, + ExecutorSubActionPushParamsSchema, + ExecutorSubActionGetIncidentParamsSchema, + ExecutorSubActionHandshakeParamsSchema, + ExecutorSubActionGetIncidentTypesParamsSchema, + ExecutorSubActionGetSeverityParamsSchema, +} from './schema'; + +import { ActionsConfigurationUtilities } from '../../actions_config'; +import { Logger } from '../../../../../../src/core/server'; + +import { IncidentConfigurationSchema } from '../case/schema'; +import { Comment } from '../case/types'; + +export type ResilientPublicConfigurationType = TypeOf< + typeof ExternalIncidentServiceConfigurationSchema +>; +export type ResilientSecretConfigurationType = TypeOf< + typeof ExternalIncidentServiceSecretConfigurationSchema +>; + +export type ExecutorParams = TypeOf; +export type ExecutorSubActionPushParams = TypeOf; + +export type IncidentConfiguration = TypeOf; + +export interface ExternalServiceCredentials { + config: Record; + secrets: Record; +} + +export interface ExternalServiceValidation { + config: (configurationUtilities: ActionsConfigurationUtilities, configObject: any) => void; + secrets: (configurationUtilities: ActionsConfigurationUtilities, secrets: any) => void; +} + +export interface ExternalServiceIncidentResponse { + id: string; + title: string; + url: string; + pushedDate: string; +} + +export interface ExternalServiceCommentResponse { + commentId: string; + pushedDate: string; + externalCommentId?: string; +} -export type ResilientPublicConfigurationType = TypeOf; -export type ResilientSecretConfigurationType = TypeOf; +export type ExternalServiceParams = Record; -interface CreateIncidentBasicRequestArgs { +export type Incident = Pick< + ExecutorSubActionPushParams, + 'description' | 'incidentTypes' | 'severityCode' +> & { name: string; - description: string; - discovered_date: number; +}; + +export interface CreateIncidentParams { + incident: Incident; +} + +export interface UpdateIncidentParams { + incidentId: string; + incident: Incident; +} + +export interface CreateCommentParams { + incidentId: string; + comment: Comment; +} + +export type GetIncidentTypesResponse = Array<{ id: string; name: string }>; +export type GetSeverityResponse = Array<{ id: string; name: string }>; + +export interface ExternalService { + getIncident: (id: string) => Promise; + createIncident: (params: CreateIncidentParams) => Promise; + updateIncident: (params: UpdateIncidentParams) => Promise; + createComment: (params: CreateCommentParams) => Promise; + getIncidentTypes: () => Promise; + getSeverity: () => Promise; } -interface Comment { - text: { format: string; content: string }; +export interface PushToServiceApiParams extends ExecutorSubActionPushParams { + externalObject: Record; } -interface CreateIncidentRequestArgs extends CreateIncidentBasicRequestArgs { - comments?: Comment[]; +export type ExecutorSubActionGetIncidentTypesParams = TypeOf< + typeof ExecutorSubActionGetIncidentTypesParamsSchema +>; + +export type ExecutorSubActionGetSeverityParams = TypeOf< + typeof ExecutorSubActionGetSeverityParamsSchema +>; + +export interface ExternalServiceApiHandlerArgs { + externalService: ExternalService; + mapping: Map | null; } +export type ExecutorSubActionGetIncidentParams = TypeOf< + typeof ExecutorSubActionGetIncidentParamsSchema +>; + +export type ExecutorSubActionHandshakeParams = TypeOf< + typeof ExecutorSubActionHandshakeParamsSchema +>; + +export interface PushToServiceApiHandlerArgs extends ExternalServiceApiHandlerArgs { + params: PushToServiceApiParams; + logger: Logger; +} + +export interface GetIncidentApiHandlerArgs extends ExternalServiceApiHandlerArgs { + params: ExecutorSubActionGetIncidentParams; +} + +export interface HandshakeApiHandlerArgs extends ExternalServiceApiHandlerArgs { + params: ExecutorSubActionHandshakeParams; +} + +export interface GetIncidentTypesHandlerArgs { + externalService: ExternalService; + params: ExecutorSubActionGetIncidentTypesParams; +} + +export interface GetSeverityHandlerArgs { + externalService: ExternalService; + params: ExecutorSubActionGetSeverityParams; +} + +export interface PushToServiceResponse extends ExternalServiceIncidentResponse { + comments?: ExternalServiceCommentResponse[]; +} + +export interface ExternalServiceApi { + handshake: (args: HandshakeApiHandlerArgs) => Promise; + pushToService: (args: PushToServiceApiHandlerArgs) => Promise; + getIncident: (args: GetIncidentApiHandlerArgs) => Promise; + incidentTypes: (args: GetIncidentTypesHandlerArgs) => Promise; + severity: (args: GetSeverityHandlerArgs) => Promise; +} + +export type ResilientExecutorResultData = + | PushToServiceResponse + | GetIncidentTypesResponse + | GetSeverityResponse; + export interface UpdateFieldText { text: string; } +export interface UpdateFieldText { + text: string; +} + +export interface UpdateIdsField { + ids: number[]; +} + +export interface UpdateIdField { + id: number; +} export interface UpdateFieldTextArea { textarea: { format: 'html' | 'text'; content: string }; @@ -34,13 +180,24 @@ export interface UpdateFieldTextArea { interface UpdateField { field: { name: string }; - old_value: UpdateFieldText | UpdateFieldTextArea; - new_value: UpdateFieldText | UpdateFieldTextArea; + old_value: UpdateFieldText | UpdateFieldTextArea | UpdateIdsField | UpdateIdField; + new_value: UpdateFieldText | UpdateFieldTextArea | UpdateIdsField | UpdateIdField; } -export type CreateIncidentRequest = CreateIncidentRequestArgs; -export type CreateCommentRequest = Comment; - export interface UpdateIncidentRequest { changes: UpdateField[]; } + +export type GetValueTextContentResponse = + | UpdateFieldText + | UpdateFieldTextArea + | UpdateIdsField + | UpdateIdField; + +export interface CreateIncidentData { + name: string; + discovered_date: number; + description?: { format: string; content: string }; + incident_type_ids?: Array<{ id: number }>; + severity_code?: { id: number }; +} diff --git a/x-pack/plugins/actions/server/builtin_action_types/resilient/validators.ts b/x-pack/plugins/actions/server/builtin_action_types/resilient/validators.ts index 7226071392bc6..a50e868cdda3d 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/resilient/validators.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/resilient/validators.ts @@ -4,8 +4,38 @@ * you may not use this file except in compliance with the Elastic License. */ -import { validateCommonConfig, validateCommonSecrets } from '../case/validators'; -import { ExternalServiceValidation } from '../case/types'; +import { isEmpty } from 'lodash'; +import { ActionsConfigurationUtilities } from '../../actions_config'; +import { + ResilientPublicConfigurationType, + ResilientSecretConfigurationType, + ExternalServiceValidation, +} from './types'; + +import * as i18n from './translations'; + +export const validateCommonConfig = ( + configurationUtilities: ActionsConfigurationUtilities, + configObject: ResilientPublicConfigurationType +) => { + if ( + configObject.incidentConfiguration !== null && + isEmpty(configObject.incidentConfiguration.mapping) + ) { + return i18n.MAPPING_EMPTY; + } + + try { + configurationUtilities.ensureUriAllowed(configObject.apiUrl); + } catch (allowedListError) { + return i18n.ALLOWED_HOSTS_ERROR(allowedListError.message); + } +}; + +export const validateCommonSecrets = ( + configurationUtilities: ActionsConfigurationUtilities, + secrets: ResilientSecretConfigurationType +) => {}; export const validate: ExternalServiceValidation = { config: validateCommonConfig, diff --git a/x-pack/plugins/actions/server/builtin_action_types/servicenow/api.ts b/x-pack/plugins/actions/server/builtin_action_types/servicenow/api.ts index c8e6147ecef46..455a71517fb4a 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/servicenow/api.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/servicenow/api.ts @@ -3,7 +3,6 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { flow } from 'lodash'; import { ExternalServiceParams, PushToServiceApiHandlerArgs, @@ -12,12 +11,11 @@ import { ExternalServiceApi, PushToServiceApiParams, PushToServiceResponse, + Incident, } from './types'; // TODO: to remove, need to support Case -import { transformers } from '../case/transformers'; -import { TransformFieldsArgs, Comment, EntityInformation } from '../case/common_types'; -import { prepareFieldsForTransformation } from '../case/utils'; +import { transformFields, transformComments, prepareFieldsForTransformation } from '../case/utils'; const handshakeHandler = async ({ externalService, @@ -62,7 +60,7 @@ const pushToServiceHandler = async ({ defaultPipes, }); - incident = transformFields({ + incident = transformFields({ params, fields, currentIncident, @@ -117,47 +115,6 @@ const pushToServiceHandler = async ({ return res; }; -export const transformFields = ({ - params, - fields, - currentIncident, -}: TransformFieldsArgs): Record => { - return fields.reduce((prev, cur) => { - const transform = flow(...cur.pipes.map((p) => transformers[p])); - return { - ...prev, - [cur.key]: transform({ - value: cur.value, - date: params.updatedAt ?? params.createdAt, - user: getEntity(params), - previousValue: currentIncident ? currentIncident[cur.key] : '', - }).value, - }; - }, {}); -}; - -export const transformComments = (comments: Comment[], pipes: string[]): Comment[] => { - return comments.map((c) => ({ - ...c, - comment: flow(...pipes.map((p) => transformers[p]))({ - value: c.comment, - date: c.updatedAt ?? c.createdAt, - user: getEntity(c), - }).value, - })); -}; - -export const getEntity = (entity: EntityInformation): string => - (entity.updatedBy != null - ? entity.updatedBy.fullName - ? entity.updatedBy.fullName - : entity.updatedBy.username - : entity.createdBy != null - ? entity.createdBy.fullName - ? entity.createdBy.fullName - : entity.createdBy.username - : '') ?? ''; - export const api: ExternalServiceApi = { handshake: handshakeHandler, pushToService: pushToServiceHandler, diff --git a/x-pack/plugins/actions/server/builtin_action_types/servicenow/mocks.ts b/x-pack/plugins/actions/server/builtin_action_types/servicenow/mocks.ts index 55a14e4528acf..f34e9714b22ce 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/servicenow/mocks.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/servicenow/mocks.ts @@ -5,7 +5,7 @@ */ import { ExternalService, PushToServiceApiParams, ExecutorSubActionPushParams } from './types'; -import { MapRecord } from '../case/common_types'; +import { MapRecord } from '../case/types'; const createMock = (): jest.Mocked => { const service = { diff --git a/x-pack/plugins/actions/server/builtin_action_types/servicenow/schema.ts b/x-pack/plugins/actions/server/builtin_action_types/servicenow/schema.ts index 921de42adfcaf..9896d4175954c 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/servicenow/schema.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/servicenow/schema.ts @@ -5,11 +5,7 @@ */ import { schema } from '@kbn/config-schema'; -import { - CommentSchema, - EntityInformation, - IncidentConfigurationSchema, -} from '../case/common_schema'; +import { CommentSchema, EntityInformation, IncidentConfigurationSchema } from '../case/schema'; export const ExternalIncidentServiceConfiguration = { apiUrl: schema.string(), diff --git a/x-pack/plugins/actions/server/builtin_action_types/servicenow/types.ts b/x-pack/plugins/actions/server/builtin_action_types/servicenow/types.ts index e8fcfac45d789..a6a0ac946fe96 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/servicenow/types.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/servicenow/types.ts @@ -16,8 +16,8 @@ import { ExecutorSubActionHandshakeParamsSchema, } from './schema'; import { ActionsConfigurationUtilities } from '../../actions_config'; -import { ExternalServiceCommentResponse } from '../case/common_types'; -import { IncidentConfigurationSchema } from '../case/common_schema'; +import { ExternalServiceCommentResponse } from '../case/types'; +import { IncidentConfigurationSchema } from '../case/schema'; import { Logger } from '../../../../../../src/core/server'; export type ServiceNowPublicConfigurationType = TypeOf< @@ -82,6 +82,13 @@ export type ExecutorSubActionHandshakeParams = TypeOf< typeof ExecutorSubActionHandshakeParamsSchema >; +export type Incident = Pick< + ExecutorSubActionPushParams, + 'description' | 'severity' | 'urgency' | 'impact' +> & { + short_description: string; +}; + export interface PushToServiceApiHandlerArgs extends ExternalServiceApiHandlerArgs { params: PushToServiceApiParams; secrets: Record; diff --git a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts index a22d7ae5cea21..545ccf82c3d78 100644 --- a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts +++ b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts @@ -13,6 +13,7 @@ import { SUPPORTED_CONNECTORS, SERVICENOW_ACTION_TYPE_ID, JIRA_ACTION_TYPE_ID, + RESILIENT_ACTION_TYPE_ID, } from '../../../../../common/constants'; /* @@ -37,8 +38,12 @@ export function initCaseConfigureGetActionConnector({ caseService, router }: Rou (action) => SUPPORTED_CONNECTORS.includes(action.actionTypeId) && // Need this filtering temporary to display only Case owned ServiceNow connectors - (![SERVICENOW_ACTION_TYPE_ID, JIRA_ACTION_TYPE_ID].includes(action.actionTypeId) || - ([SERVICENOW_ACTION_TYPE_ID, JIRA_ACTION_TYPE_ID].includes(action.actionTypeId) && + (![SERVICENOW_ACTION_TYPE_ID, JIRA_ACTION_TYPE_ID, RESILIENT_ACTION_TYPE_ID].includes( + action.actionTypeId + ) || + ([SERVICENOW_ACTION_TYPE_ID, JIRA_ACTION_TYPE_ID, RESILIENT_ACTION_TYPE_ID].includes( + action.actionTypeId + ) && action.config?.isCaseOwned === true)) ); return response.ok({ body: results }); diff --git a/x-pack/plugins/dashboard_mode/kibana.json b/x-pack/plugins/dashboard_mode/kibana.json index 4777b9b25be23..81e2073b5c7fd 100644 --- a/x-pack/plugins/dashboard_mode/kibana.json +++ b/x-pack/plugins/dashboard_mode/kibana.json @@ -9,6 +9,7 @@ "optionalPlugins": ["security"], "requiredPlugins": [ "kibanaLegacy", + "urlForwarding", "dashboard" ], "server": true, diff --git a/x-pack/plugins/dashboard_mode/public/plugin.ts b/x-pack/plugins/dashboard_mode/public/plugin.ts index d988de5851cf5..96486bd6da8c8 100644 --- a/x-pack/plugins/dashboard_mode/public/plugin.ts +++ b/x-pack/plugins/dashboard_mode/public/plugin.ts @@ -7,6 +7,7 @@ import { trimStart } from 'lodash'; import { CoreSetup } from 'kibana/public'; import { KibanaLegacyStart } from '../../../../src/plugins/kibana_legacy/public'; +import { UrlForwardingStart } from '../../../../src/plugins/url_forwarding/public'; import { createDashboardEditUrl, DashboardConstants, @@ -22,7 +23,11 @@ function dashboardAppIdPrefix() { return trimStart(createDashboardEditUrl(''), '/'); } -function migratePath(currentHash: string, kibanaLegacy: KibanaLegacyStart) { +function migratePath( + currentHash: string, + kibanaLegacy: KibanaLegacyStart, + urlForwarding: UrlForwardingStart +) { if (currentHash === '' || currentHash === '#' || currentHash === '#/') { return `#${defaultUrl(kibanaLegacy.config.defaultAppId || '')}`; } @@ -30,7 +35,7 @@ function migratePath(currentHash: string, kibanaLegacy: KibanaLegacyStart) { return currentHash; } - const forwards = kibanaLegacy.getForwards(); + const forwards = urlForwarding.getForwards(); if (currentHash.startsWith('#/dashboards')) { const { rewritePath: migrateListingPath } = forwards.find( @@ -46,18 +51,18 @@ function migratePath(currentHash: string, kibanaLegacy: KibanaLegacyStart) { } export const plugin = () => ({ - setup(core: CoreSetup<{ kibanaLegacy: KibanaLegacyStart }>) { + setup(core: CoreSetup<{ kibanaLegacy: KibanaLegacyStart; urlForwarding: UrlForwardingStart }>) { core.application.register({ id: 'dashboard_mode', title: 'Dashboard mode', navLinkStatus: AppNavLinkStatus.hidden, mount: async () => { - const [coreStart, { kibanaLegacy }] = await core.getStartServices(); + const [coreStart, { kibanaLegacy, urlForwarding }] = await core.getStartServices(); kibanaLegacy.dashboardConfig.turnHideWriteControlsOn(); coreStart.chrome.navLinks.showOnly('dashboards'); setTimeout(() => { coreStart.application.navigateToApp('dashboards', { - path: migratePath(window.location.hash, kibanaLegacy), + path: migratePath(window.location.hash, kibanaLegacy, urlForwarding), }); }, 0); return () => {}; diff --git a/x-pack/plugins/data_enhanced/kibana.json b/x-pack/plugins/data_enhanced/kibana.json index 637af39339e27..5ded0f8f0dec3 100644 --- a/x-pack/plugins/data_enhanced/kibana.json +++ b/x-pack/plugins/data_enhanced/kibana.json @@ -6,10 +6,11 @@ "xpack", "data_enhanced" ], "requiredPlugins": [ - "data" + "data", + "features" ], - "optionalPlugins": ["kibanaReact", "kibanaUtils", "usageCollection"], + "optionalPlugins": ["kibanaUtils", "usageCollection"], "server": true, "ui": true, - "requiredBundles": ["kibanaReact", "kibanaUtils"] + "requiredBundles": ["kibanaUtils"] } diff --git a/x-pack/plugins/data_enhanced/public/search/long_query_notification.tsx b/x-pack/plugins/data_enhanced/public/search/long_query_notification.tsx deleted file mode 100644 index 325cf1145fa5f..0000000000000 --- a/x-pack/plugins/data_enhanced/public/search/long_query_notification.tsx +++ /dev/null @@ -1,47 +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 { EuiButton, EuiButtonEmpty, EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; -import React from 'react'; -import { toMountPoint } from '../../../../../src/plugins/kibana_react/public'; - -interface Props { - cancel: () => void; - runBeyondTimeout: () => void; -} - -export function getLongQueryNotification(props: Props) { - return toMountPoint( - - ); -} - -export function LongQueryNotification(props: Props) { - return ( -
- - - - - - - - - - - - - -
- ); -} diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts index 261e03887acdb..af2fc85602541 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts @@ -60,9 +60,6 @@ describe('EnhancedSearchInterceptor', () => { mockUsageCollector = { trackQueryTimedOut: jest.fn(), trackQueriesCancelled: jest.fn(), - trackLongQueryPopupShown: jest.fn(), - trackLongQueryDialogDismissed: jest.fn(), - trackLongQueryRunBeyondTimeout: jest.fn(), }; const mockPromise = new Promise((resolve) => { @@ -390,88 +387,4 @@ describe('EnhancedSearchInterceptor', () => { expect(mockUsageCollector.trackQueriesCancelled).toBeCalledTimes(1); }); }); - - describe('runBeyondTimeout', () => { - const timedResponses = [ - { - time: 250, - value: { - isPartial: true, - isRunning: true, - id: 1, - rawResponse: { - took: 1, - }, - }, - }, - { - time: 2000, - value: { - isPartial: false, - isRunning: false, - id: 1, - rawResponse: { - took: 1, - }, - }, - }, - ]; - - test('times out if runBeyondTimeout is not called', async () => { - mockFetchImplementation(timedResponses); - - const response = searchInterceptor.search({}); - response.subscribe({ next, error }); - - await timeTravel(250); - - expect(next).toHaveBeenCalled(); - expect(next.mock.calls[0][0]).toStrictEqual(timedResponses[0].value); - - await timeTravel(750); - - expect(error).toHaveBeenCalled(); - expect(error.mock.calls[0][0]).toBeInstanceOf(AbortError); - }); - - test('times out if runBeyondTimeout is called too late', async () => { - mockFetchImplementation(timedResponses); - - const response = searchInterceptor.search({}); - response.subscribe({ next, error }); - setTimeout(() => searchInterceptor.runBeyondTimeout(), 1100); - - await timeTravel(250); - - expect(next).toHaveBeenCalled(); - expect(next.mock.calls[0][0]).toStrictEqual(timedResponses[0].value); - - await timeTravel(750); - - expect(error).toHaveBeenCalled(); - expect(error.mock.calls[0][0]).toBeInstanceOf(AbortError); - }); - - test('should prevent the request from timing out', async () => { - mockFetchImplementation(timedResponses); - - const response = searchInterceptor.search({}, { pollInterval: 0 }); - response.subscribe({ next, error, complete }); - setTimeout(() => searchInterceptor.runBeyondTimeout(), 500); - - await timeTravel(250); - - expect(next).toHaveBeenCalled(); - expect(next.mock.calls[0][0]).toStrictEqual(timedResponses[0].value); - - await timeTravel(250); // Run beyond timeout - await timeTravel(1750); // Final response - - expect(next).toHaveBeenCalledTimes(2); - expect(next.mock.calls[0][0]).toStrictEqual(timedResponses[0].value); - expect(next.mock.calls[1][0]).toStrictEqual(timedResponses[1].value); - expect(error).not.toHaveBeenCalled(); - expect(mockUsageCollector.trackLongQueryRunBeyondTimeout).toBeCalledTimes(1); - }); - }); }); diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts index 61cf579d3136b..f7ae9fc6d0f91 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts @@ -6,7 +6,8 @@ import { throwError, EMPTY, timer, from, Subscription } from 'rxjs'; import { mergeMap, expand, takeUntil, finalize, tap } from 'rxjs/operators'; -import { getLongQueryNotification } from './long_query_notification'; +import { debounce } from 'lodash'; +import { i18n } from '@kbn/i18n'; import { SearchInterceptor, SearchInterceptorDeps, @@ -42,38 +43,11 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { * Abort our `AbortController`, which in turn aborts any intercepted searches. */ public cancelPending = () => { - this.hideToast(); this.abortController.abort(); this.abortController = new AbortController(); if (this.deps.usageCollector) this.deps.usageCollector.trackQueriesCancelled(); }; - /** - * Un-schedule timing out all of the searches intercepted. - */ - public runBeyondTimeout = () => { - this.hideToast(); - this.timeoutSubscriptions.unsubscribe(); - if (this.deps.usageCollector) this.deps.usageCollector.trackLongQueryRunBeyondTimeout(); - }; - - protected showToast = () => { - if (this.longRunningToast) return; - this.longRunningToast = this.deps.toasts.addInfo( - { - title: 'Your query is taking a while', - text: getLongQueryNotification({ - cancel: this.cancelPending, - runBeyondTimeout: this.runBeyondTimeout, - }), - }, - { - toastLifeTimeMs: 1000000, - } - ); - if (this.deps.usageCollector) this.deps.usageCollector.trackLongQueryPopupShown(); - }; - public search( request: IAsyncSearchRequest, { pollInterval = 1000, ...options }: IAsyncSearchOptions = {} @@ -127,4 +101,28 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { }) ); } + + // Right now we are debouncing but we will hook this up with background sessions to show only one + // error notification per session. + protected showTimeoutError = debounce( + (e: Error) => { + const message = this.application.capabilities.advancedSettings?.save + ? i18n.translate('xpack.data.search.timeoutIncreaseSetting', { + defaultMessage: + 'One or more queries timed out. Increase run time with the search.timeout advanced setting.', + }) + : i18n.translate('xpack.data.search.timeoutContactAdmin', { + defaultMessage: + 'One or more queries timed out. Contact your system administrator to increase the run time.', + }); + this.deps.toasts.addError(e, { + title: 'Timed out', + toastMessage: message, + }); + }, + 60000, + { + leading: true, + } + ); } diff --git a/x-pack/plugins/data_enhanced/server/plugin.ts b/x-pack/plugins/data_enhanced/server/plugin.ts index 3b05e83d208b7..a1dff00ddfdd3 100644 --- a/x-pack/plugins/data_enhanced/server/plugin.ts +++ b/x-pack/plugins/data_enhanced/server/plugin.ts @@ -18,8 +18,8 @@ import { } from '../../../../src/plugins/data/server'; import { enhancedEsSearchStrategyProvider } from './search'; import { UsageCollectionSetup } from '../../../../src/plugins/usage_collection/server'; -import { ENHANCED_ES_SEARCH_STRATEGY } from '../common'; import { getUiSettings } from './ui_settings'; +import { ENHANCED_ES_SEARCH_STRATEGY } from '../common'; interface SetupDependencies { data: DataPluginSetup; diff --git a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts index eda6178dc8e5b..72ea1f096e8fb 100644 --- a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts +++ b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts @@ -7,6 +7,7 @@ import { first } from 'rxjs/operators'; import { SearchResponse } from 'elasticsearch'; import { Observable } from 'rxjs'; +import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; import { SharedGlobalConfig, RequestHandlerContext, Logger } from '../../../../../src/core/server'; import { getTotalLoaded, @@ -40,8 +41,8 @@ export const enhancedEsSearchStrategyProvider = ( try { const response = isAsync - ? await asyncSearch(context, request) - : await rollupSearch(context, request); + ? await asyncSearch(context, request, options) + : await rollupSearch(context, request, options); if ( usage && @@ -69,9 +70,10 @@ export const enhancedEsSearchStrategyProvider = ( async function asyncSearch( context: RequestHandlerContext, - request: IEnhancedEsSearchRequest + request: IEnhancedEsSearchRequest, + options?: ISearchOptions ): Promise { - let esResponse; + let promise: TransportRequestPromise; const esClient = context.core.elasticsearch.client.asCurrentUser; const uiSettingsClient = await context.core.uiSettings.client; @@ -89,14 +91,17 @@ export const enhancedEsSearchStrategyProvider = ( ...request.params, }); - esResponse = await esClient.asyncSearch.submit(submitOptions); + promise = esClient.asyncSearch.submit(submitOptions); } else { - esResponse = await esClient.asyncSearch.get({ + promise = esClient.asyncSearch.get({ id: request.id, ...toSnakeCase(asyncOptions), }); } + // Temporary workaround until https://github.com/elastic/elasticsearch-js/issues/1297 + if (options?.abortSignal) options.abortSignal.addEventListener('abort', () => promise.abort()); + const esResponse = await promise; const { id, response, is_partial: isPartial, is_running: isRunning } = esResponse.body; return { id, @@ -109,7 +114,8 @@ export const enhancedEsSearchStrategyProvider = ( const rollupSearch = async function ( context: RequestHandlerContext, - request: IEnhancedEsSearchRequest + request: IEnhancedEsSearchRequest, + options?: ISearchOptions ): Promise { const esClient = context.core.elasticsearch.client.asCurrentUser; const uiSettingsClient = await context.core.uiSettings.client; @@ -123,13 +129,17 @@ export const enhancedEsSearchStrategyProvider = ( ...params, }); - const esResponse = await esClient.transport.request({ + const promise = esClient.transport.request({ method, path, body, querystring, }); + // Temporary workaround until https://github.com/elastic/elasticsearch-js/issues/1297 + if (options?.abortSignal) options.abortSignal.addEventListener('abort', () => promise.abort()); + const esResponse = await promise; + const response = esResponse.body as SearchResponse; return { rawResponse: response, diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts index f8d66b8ecac27..18834f55af0a5 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts @@ -555,7 +555,18 @@ describe('#bulkUpdate', () => { }); describe('namespace', () => { - const doTest = async (namespace: string, expectNamespaceInDescriptor: boolean) => { + interface TestParams { + optionsNamespace: string | undefined; + objectNamespace: string | undefined; + expectOptionsNamespaceInDescriptor: boolean; + expectObjectNamespaceInDescriptor: boolean; + } + const doTest = async ({ + optionsNamespace, + objectNamespace, + expectOptionsNamespaceInDescriptor, + expectObjectNamespaceInDescriptor, + }: TestParams) => { const docs = [ { id: 'some-id', @@ -566,12 +577,13 @@ describe('#bulkUpdate', () => { attrThree: 'three', }, version: 'some-version', + namespace: objectNamespace, }, ]; - const options = { namespace }; + const options = { namespace: optionsNamespace }; mockBaseClient.bulkUpdate.mockResolvedValue({ - saved_objects: docs.map((doc) => ({ ...doc, references: undefined })), + saved_objects: docs.map(({ namespace, ...doc }) => ({ ...doc, references: undefined })), }); await expect(wrapper.bulkUpdate(docs, options)).resolves.toEqual({ @@ -594,7 +606,11 @@ describe('#bulkUpdate', () => { { type: 'known-type', id: 'some-id', - namespace: expectNamespaceInDescriptor ? namespace : undefined, + namespace: expectObjectNamespaceInDescriptor + ? objectNamespace + : expectOptionsNamespaceInDescriptor + ? optionsNamespace + : undefined, }, { attrOne: 'one', attrSecret: 'secret', attrThree: 'three' }, { user: mockAuthenticatedUser() } @@ -612,7 +628,7 @@ describe('#bulkUpdate', () => { attrThree: 'three', }, version: 'some-version', - + namespace: objectNamespace, references: undefined, }, ], @@ -620,13 +636,46 @@ describe('#bulkUpdate', () => { ); }; - it('uses `namespace` to encrypt attributes if it is specified when type is single-namespace', async () => { - await doTest('some-namespace', true); + it('does not use options `namespace` or object `namespace` to encrypt attributes if neither are specified', async () => { + await doTest({ + optionsNamespace: undefined, + objectNamespace: undefined, + expectOptionsNamespaceInDescriptor: false, + expectObjectNamespaceInDescriptor: false, + }); }); - it('does not use `namespace` to encrypt attributes if it is specified when type is not single-namespace', async () => { - mockBaseTypeRegistry.isSingleNamespace.mockReturnValue(false); - await doTest('some-namespace', false); + describe('with a single-namespace type', () => { + it('uses options `namespace` to encrypt attributes if it is specified and object `namespace` is not', async () => { + await doTest({ + optionsNamespace: 'some-namespace', + objectNamespace: undefined, + expectOptionsNamespaceInDescriptor: true, + expectObjectNamespaceInDescriptor: false, + }); + }); + + it('uses object `namespace` to encrypt attributes if it is specified', async () => { + // object namespace supersedes options namespace + await doTest({ + optionsNamespace: 'some-namespace', + objectNamespace: 'another-namespace', + expectOptionsNamespaceInDescriptor: false, + expectObjectNamespaceInDescriptor: true, + }); + }); + }); + + describe('with a non-single-namespace type', () => { + it('does not use object `namespace` or options `namespace` to encrypt attributes if it is specified', async () => { + mockBaseTypeRegistry.isSingleNamespace.mockReturnValue(false); + await doTest({ + optionsNamespace: 'some-namespace', + objectNamespace: 'another-namespace', + expectOptionsNamespaceInDescriptor: false, + expectObjectNamespaceInDescriptor: false, + }); + }); }); }); diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts index a2725cbc6a274..0eeb9943b5be9 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts @@ -150,14 +150,14 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon // sequential processing. const encryptedObjects = await Promise.all( objects.map(async (object) => { - const { type, id, attributes } = object; + const { type, id, attributes, namespace: objectNamespace } = object; if (!this.options.service.isRegistered(type)) { return object; } const namespace = getDescriptorNamespace( this.options.baseTypeRegistry, type, - options?.namespace + objectNamespace ?? options?.namespace ); return { ...object, diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.ts index b2842df909a1d..7201f13fb930b 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ISavedObjectTypeRegistry } from 'kibana/server'; +import { ISavedObjectTypeRegistry, SavedObjectsUtils } from '../../../../../src/core/server'; export const getDescriptorNamespace = ( typeRegistry: ISavedObjectTypeRegistry, @@ -12,5 +12,12 @@ export const getDescriptorNamespace = ( namespace?: string ) => { const descriptorNamespace = typeRegistry.isSingleNamespace(type) ? namespace : undefined; - return descriptorNamespace === 'default' ? undefined : descriptorNamespace; + return normalizeNamespace(descriptorNamespace); }; + +/** + * Ensure that a namespace is always in its namespace ID representation. + * This allows `'default'` to be used interchangeably with `undefined`. + */ +const normalizeNamespace = (namespace?: string) => + namespace === undefined ? namespace : SavedObjectsUtils.namespaceStringToId(namespace); diff --git a/x-pack/plugins/ingest_manager/common/types/models/agent.ts b/x-pack/plugins/ingest_manager/common/types/models/agent.ts index 2b8a306577e7d..a204373fe2e56 100644 --- a/x-pack/plugins/ingest_manager/common/types/models/agent.ts +++ b/x-pack/plugins/ingest_manager/common/types/models/agent.ts @@ -21,7 +21,8 @@ export type AgentStatus = | 'unenrolling' | 'degraded'; -export type AgentActionType = 'CONFIG_CHANGE' | 'DATA_DUMP' | 'RESUME' | 'PAUSE' | 'UNENROLL'; +export type AgentActionType = 'CONFIG_CHANGE' | 'UNENROLL'; + export interface NewAgentAction { type: AgentActionType; data?: any; @@ -29,20 +30,44 @@ export interface NewAgentAction { } export interface AgentAction extends NewAgentAction { + type: AgentActionType; + data?: any; + sent_at?: string; id: string; agent_id: string; created_at: string; + ack_data?: any; +} + +export interface AgentPolicyAction extends NewAgentAction { + id: string; + type: AgentActionType; + data?: any; + policy_id: string; + policy_revision: number; + created_at: string; + ack_data?: any; } -export interface AgentActionSOAttributes { +interface CommonAgentActionSOAttributes { type: AgentActionType; sent_at?: string; timestamp?: string; created_at: string; - agent_id: string; data?: string; + ack_data?: string; } +export type AgentActionSOAttributes = CommonAgentActionSOAttributes & { + agent_id: string; +}; +export type AgentPolicyActionSOAttributes = CommonAgentActionSOAttributes & { + policy_id: string; + policy_revision: number; +}; + +export type BaseAgentActionSOAttributes = AgentActionSOAttributes | AgentPolicyActionSOAttributes; + export interface NewAgentEvent { type: 'STATE' | 'ERROR' | 'ACTION_RESULT' | 'ACTION'; subtype: // State diff --git a/x-pack/plugins/ingest_manager/common/types/rest_spec/agent.ts b/x-pack/plugins/ingest_manager/common/types/rest_spec/agent.ts index cf8d3ab1c908a..54cdeade3764e 100644 --- a/x-pack/plugins/ingest_manager/common/types/rest_spec/agent.ts +++ b/x-pack/plugins/ingest_manager/common/types/rest_spec/agent.ts @@ -7,11 +7,11 @@ import { Agent, AgentAction, + NewAgentAction, NewAgentEvent, AgentEvent, AgentStatus, AgentType, - NewAgentAction, } from '../models'; export interface GetAgentsRequest { diff --git a/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts index b81d44c40f8eb..12a0956b79155 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts @@ -10,7 +10,6 @@ import { RequestHandler } from 'kibana/server'; import { TypeOf } from '@kbn/config-schema'; import { PostNewAgentActionRequestSchema } from '../../types/rest_spec'; import { ActionsService } from '../../services/agents'; -import { NewAgentAction } from '../../../common/types/models'; import { PostNewAgentActionResponse } from '../../../common/types/rest_spec'; export const postNewAgentActionHandlerBuilder = function ( @@ -26,7 +25,7 @@ export const postNewAgentActionHandlerBuilder = function ( const agent = await actionsService.getAgent(soClient, request.params.agentId); - const newAgentAction = request.body.action as NewAgentAction; + const newAgentAction = request.body.action; const savedAgentAction = await actionsService.createAgentAction(soClient, { created_at: new Date().toISOString(), diff --git a/x-pack/plugins/ingest_manager/server/saved_objects/index.ts b/x-pack/plugins/ingest_manager/server/saved_objects/index.ts index aff8e607622d4..e86f7b24e2c78 100644 --- a/x-pack/plugins/ingest_manager/server/saved_objects/index.ts +++ b/x-pack/plugins/ingest_manager/server/saved_objects/index.ts @@ -98,8 +98,11 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { mappings: { properties: { agent_id: { type: 'keyword' }, + policy_id: { type: 'keyword' }, + policy_revision: { type: 'integer' }, type: { type: 'keyword' }, data: { type: 'binary' }, + ack_data: { type: 'text' }, sent_at: { type: 'date' }, created_at: { type: 'date' }, }, diff --git a/x-pack/plugins/ingest_manager/server/services/agent_policy.ts b/x-pack/plugins/ingest_manager/server/services/agent_policy.ts index a03a3b7f59fba..938cfb4351630 100644 --- a/x-pack/plugins/ingest_manager/server/services/agent_policy.ts +++ b/x-pack/plugins/ingest_manager/server/services/agent_policy.ts @@ -21,7 +21,7 @@ import { ListWithKuery, } from '../types'; import { DeleteAgentPolicyResponse, storedPackagePoliciesToAgentInputs } from '../../common'; -import { listAgents } from './agents'; +import { createAgentPolicyAction, listAgents } from './agents'; import { packagePolicyService } from './package_policy'; import { outputService } from './output'; import { agentPolicyUpdateEventHandler } from './agent_policy_update'; @@ -67,6 +67,10 @@ class AgentPolicyService { updated_by: user ? user.username : 'system', }); + if (options.bumpRevision) { + await this.triggerAgentPolicyUpdatedEvent(soClient, 'updated', id); + } + return (await this.get(soClient, id)) as AgentPolicy; } @@ -383,6 +387,32 @@ class AgentPolicyService { }; } + public async createFleetPolicyChangeAction( + soClient: SavedObjectsClientContract, + agentPolicyId: string + ) { + const policy = await agentPolicyService.getFullAgentPolicy(soClient, agentPolicyId); + if (!policy || !policy.revision) { + return; + } + const packages = policy.inputs.reduce((acc, input) => { + const packageName = input.meta?.package?.name; + if (packageName && acc.indexOf(packageName) < 0) { + acc.push(packageName); + } + return acc; + }, []); + + await createAgentPolicyAction(soClient, { + type: 'CONFIG_CHANGE', + data: { config: policy } as any, + ack_data: { packages }, + created_at: new Date().toISOString(), + policy_id: policy.id, + policy_revision: policy.revision, + }); + } + public async getFullAgentPolicy( soClient: SavedObjectsClientContract, id: string, diff --git a/x-pack/plugins/ingest_manager/server/services/agent_policy_update.ts b/x-pack/plugins/ingest_manager/server/services/agent_policy_update.ts index 3c743dd957f62..ff20e25e5bf0d 100644 --- a/x-pack/plugins/ingest_manager/server/services/agent_policy_update.ts +++ b/x-pack/plugins/ingest_manager/server/services/agent_policy_update.ts @@ -8,6 +8,7 @@ import { SavedObjectsClientContract } from 'src/core/server'; import { generateEnrollmentAPIKey, deleteEnrollmentApiKeyForAgentPolicyId } from './api_keys'; import { unenrollForAgentPolicyId } from './agents'; import { outputService } from './output'; +import { agentPolicyService } from './agent_policy'; export async function agentPolicyUpdateEventHandler( soClient: SavedObjectsClientContract, @@ -15,8 +16,9 @@ export async function agentPolicyUpdateEventHandler( agentPolicyId: string ) { const adminUser = await outputService.getAdminUser(soClient); - // If no admin user fleet is not enabled just skip this hook - if (!adminUser) { + const outputId = await outputService.getDefaultOutputId(soClient); + // If no admin user and no default output fleet is not enabled just skip this hook + if (!adminUser || !outputId) { return; } @@ -24,6 +26,11 @@ export async function agentPolicyUpdateEventHandler( await generateEnrollmentAPIKey(soClient, { agentPolicyId, }); + await agentPolicyService.createFleetPolicyChangeAction(soClient, agentPolicyId); + } + + if (action === 'updated') { + await agentPolicyService.createFleetPolicyChangeAction(soClient, agentPolicyId); } if (action === 'deleted') { diff --git a/x-pack/plugins/ingest_manager/server/services/agents/acks.test.ts b/x-pack/plugins/ingest_manager/server/services/agents/acks.test.ts index 80fdc305d0ba7..866aa587b8a56 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/acks.test.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/acks.test.ts @@ -6,45 +6,19 @@ import Boom from 'boom'; import { SavedObjectsBulkResponse } from 'kibana/server'; import { savedObjectsClientMock } from 'src/core/server/mocks'; -import { encryptedSavedObjectsMock } from '../../../../../plugins/encrypted_saved_objects/server/mocks'; import { Agent, - AgentAction, AgentActionSOAttributes, + BaseAgentActionSOAttributes, AgentEvent, } from '../../../common/types/models'; import { AGENT_TYPE_PERMANENT, AGENT_ACTION_SAVED_OBJECT_TYPE } from '../../../common/constants'; import { acknowledgeAgentActions } from './acks'; -import { appContextService } from '../app_context'; -import { IngestManagerAppContext } from '../../plugin'; describe('test agent acks services', () => { it('should succeed on valid and matched actions', async () => { const mockSavedObjectsClient = savedObjectsClientMock.create(); - const mockStartEncryptedSOPlugin = encryptedSavedObjectsMock.createStart(); - appContextService.start(({ - encryptedSavedObjectsStart: mockStartEncryptedSOPlugin, - } as unknown) as IngestManagerAppContext); - - const [ - { value: mockStartEncryptedSOClient }, - ] = mockStartEncryptedSOPlugin.getClient.mock.results; - - mockStartEncryptedSOClient.getDecryptedAsInternalUser.mockReturnValue( - Promise.resolve({ - id: 'action1', - references: [], - type: AGENT_ACTION_SAVED_OBJECT_TYPE, - attributes: { - type: 'CONFIG_CHANGE', - agent_id: 'id', - sent_at: '2020-03-14T19:45:02.620Z', - timestamp: '2019-01-04T14:32:03.36764-05:00', - created_at: '2020-03-14T19:45:02.620Z', - }, - }) - ); mockSavedObjectsClient.bulkGet.mockReturnValue( Promise.resolve({ @@ -65,7 +39,7 @@ describe('test agent acks services', () => { } as SavedObjectsBulkResponse) ); - const agentActions = await acknowledgeAgentActions( + await acknowledgeAgentActions( mockSavedObjectsClient, ({ id: 'id', @@ -81,125 +55,32 @@ describe('test agent acks services', () => { } as AgentEvent, ] ); - expect(agentActions).toEqual([ - ({ - type: 'CONFIG_CHANGE', - id: 'action1', - agent_id: 'id', - sent_at: '2020-03-14T19:45:02.620Z', - timestamp: '2019-01-04T14:32:03.36764-05:00', - created_at: '2020-03-14T19:45:02.620Z', - } as unknown) as AgentAction, - ]); }); it('should update config field on the agent if a policy change is acknowledged', async () => { const mockSavedObjectsClient = savedObjectsClientMock.create(); - const mockStartEncryptedSOPlugin = encryptedSavedObjectsMock.createStart(); - appContextService.start(({ - encryptedSavedObjectsStart: mockStartEncryptedSOPlugin, - } as unknown) as IngestManagerAppContext); - const [ - { value: mockStartEncryptedSOClient }, - ] = mockStartEncryptedSOPlugin.getClient.mock.results; - - mockStartEncryptedSOClient.getDecryptedAsInternalUser.mockReturnValue( - Promise.resolve({ - id: 'action1', - references: [], - type: AGENT_ACTION_SAVED_OBJECT_TYPE, - attributes: { - type: 'CONFIG_CHANGE', - agent_id: 'id', - sent_at: '2020-03-14T19:45:02.620Z', - timestamp: '2019-01-04T14:32:03.36764-05:00', - created_at: '2020-03-14T19:45:02.620Z', - data: JSON.stringify({ - config: { - id: 'policy1', - revision: 4, - settings: { - monitoring: { - enabled: true, - use_output: 'default', - logs: true, - metrics: true, - }, - }, - outputs: { - default: { - type: 'elasticsearch', - hosts: ['http://localhost:9200'], - }, - }, - inputs: [ - { - id: 'f2293360-b57c-11ea-8bd3-7bd51e425399', - name: 'system-1', - type: 'logs', - use_output: 'default', - meta: { - package: { - name: 'system', - version: '0.3.0', - }, - }, - dataset: { - namespace: 'default', - }, - streams: [ - { - id: 'logs-system.syslog', - dataset: { - name: 'system.syslog', - }, - paths: ['/var/log/messages*', '/var/log/syslog*'], - exclude_files: ['.gz$'], - multiline: { - pattern: '^\\s', - match: 'after', - }, - processors: [ - { - add_locale: null, - }, - { - add_fields: { - target: '', - fields: { - 'ecs.version': '1.5.0', - }, - }, - }, - ], - }, - ], - }, - ], - }, - }), - }, - }) - ); + const actionAttributes = { + type: 'CONFIG_CHANGE', + policy_id: 'policy1', + policy_revision: 4, + sent_at: '2020-03-14T19:45:02.620Z', + timestamp: '2019-01-04T14:32:03.36764-05:00', + created_at: '2020-03-14T19:45:02.620Z', + ack_data: JSON.stringify({ packages: ['system'] }), + }; mockSavedObjectsClient.bulkGet.mockReturnValue( Promise.resolve({ saved_objects: [ { - id: 'action1', + id: 'action2', references: [], type: AGENT_ACTION_SAVED_OBJECT_TYPE, - attributes: { - type: 'CONFIG_CHANGE', - agent_id: 'id', - sent_at: '2020-03-14T19:45:02.620Z', - timestamp: '2019-01-04T14:32:03.36764-05:00', - created_at: '2020-03-14T19:45:02.620Z', - }, + attributes: actionAttributes, }, ], - } as SavedObjectsBulkResponse) + } as SavedObjectsBulkResponse) ); await acknowledgeAgentActions( @@ -214,13 +95,13 @@ describe('test agent acks services', () => { type: 'ACTION_RESULT', subtype: 'CONFIG', timestamp: '2019-01-04T14:32:03.36764-05:00', - action_id: 'action1', + action_id: 'action2', agent_id: 'id', } as AgentEvent, ] ); expect(mockSavedObjectsClient.bulkUpdate).toBeCalled(); - expect(mockSavedObjectsClient.bulkUpdate.mock.calls[0][0]).toHaveLength(2); + expect(mockSavedObjectsClient.bulkUpdate.mock.calls[0][0]).toHaveLength(1); expect(mockSavedObjectsClient.bulkUpdate.mock.calls[0][0][0]).toMatchInlineSnapshot(` Object { "attributes": Object { @@ -237,111 +118,25 @@ describe('test agent acks services', () => { it('should not update config field on the agent if a policy change for an old revision is acknowledged', async () => { const mockSavedObjectsClient = savedObjectsClientMock.create(); - const mockStartEncryptedSOPlugin = encryptedSavedObjectsMock.createStart(); - appContextService.start(({ - encryptedSavedObjectsStart: mockStartEncryptedSOPlugin, - } as unknown) as IngestManagerAppContext); - - const [ - { value: mockStartEncryptedSOClient }, - ] = mockStartEncryptedSOPlugin.getClient.mock.results; - - mockStartEncryptedSOClient.getDecryptedAsInternalUser.mockReturnValue( - Promise.resolve({ - id: 'action1', - references: [], - type: AGENT_ACTION_SAVED_OBJECT_TYPE, - attributes: { - type: 'CONFIG_CHANGE', - agent_id: 'id', - sent_at: '2020-03-14T19:45:02.620Z', - timestamp: '2019-01-04T14:32:03.36764-05:00', - created_at: '2020-03-14T19:45:02.620Z', - data: JSON.stringify({ - config: { - id: 'policy1', - revision: 4, - settings: { - monitoring: { - enabled: true, - use_output: 'default', - logs: true, - metrics: true, - }, - }, - outputs: { - default: { - type: 'elasticsearch', - hosts: ['http://localhost:9200'], - }, - }, - inputs: [ - { - id: 'f2293360-b57c-11ea-8bd3-7bd51e425399', - name: 'system-1', - type: 'logs', - use_output: 'default', - meta: { - package: { - name: 'system', - version: '0.3.0', - }, - }, - dataset: { - namespace: 'default', - }, - streams: [ - { - id: 'logs-system.syslog', - dataset: { - name: 'system.syslog', - }, - paths: ['/var/log/messages*', '/var/log/syslog*'], - exclude_files: ['.gz$'], - multiline: { - pattern: '^\\s', - match: 'after', - }, - processors: [ - { - add_locale: null, - }, - { - add_fields: { - target: '', - fields: { - 'ecs.version': '1.5.0', - }, - }, - }, - ], - }, - ], - }, - ], - }, - }), - }, - }) - ); mockSavedObjectsClient.bulkGet.mockReturnValue( Promise.resolve({ saved_objects: [ { - id: 'action1', + id: 'action3', references: [], type: AGENT_ACTION_SAVED_OBJECT_TYPE, attributes: { type: 'CONFIG_CHANGE', - agent_id: 'id', sent_at: '2020-03-14T19:45:02.620Z', timestamp: '2019-01-04T14:32:03.36764-05:00', created_at: '2020-03-14T19:45:02.620Z', + policy_id: 'policy1', + policy_revision: 99, }, }, ], - } as SavedObjectsBulkResponse) + } as SavedObjectsBulkResponse) ); await acknowledgeAgentActions( @@ -357,13 +152,13 @@ describe('test agent acks services', () => { type: 'ACTION_RESULT', subtype: 'CONFIG', timestamp: '2019-01-04T14:32:03.36764-05:00', - action_id: 'action1', + action_id: 'action3', agent_id: 'id', } as AgentEvent, ] ); expect(mockSavedObjectsClient.bulkUpdate).toBeCalled(); - expect(mockSavedObjectsClient.bulkUpdate.mock.calls[0][0]).toHaveLength(1); + expect(mockSavedObjectsClient.bulkUpdate.mock.calls[0][0]).toHaveLength(0); }); it('should fail for actions that cannot be found on agent actions list', async () => { @@ -372,7 +167,7 @@ describe('test agent acks services', () => { Promise.resolve({ saved_objects: [ { - id: 'action1', + id: 'action4', error: { message: 'Not found', statusCode: 404, @@ -394,7 +189,7 @@ describe('test agent acks services', () => { type: 'ACTION_RESULT', subtype: 'CONFIG', timestamp: '2019-01-04T14:32:03.36764-05:00', - action_id: 'action2', + action_id: 'action4', agent_id: 'id', } as unknown) as AgentEvent, ] @@ -412,7 +207,7 @@ describe('test agent acks services', () => { Promise.resolve({ saved_objects: [ { - id: 'action1', + id: 'action5', references: [], type: AGENT_ACTION_SAVED_OBJECT_TYPE, attributes: { @@ -439,7 +234,7 @@ describe('test agent acks services', () => { type: 'ACTION', subtype: 'FAILED', timestamp: '2019-01-04T14:32:03.36764-05:00', - action_id: 'action1', + action_id: 'action5', agent_id: 'id', } as unknown) as AgentEvent, ] diff --git a/x-pack/plugins/ingest_manager/server/services/agents/acks.ts b/x-pack/plugins/ingest_manager/server/services/agents/acks.ts index 87572ce405ee7..d29dfcec7ef30 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/acks.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/acks.ts @@ -11,14 +11,15 @@ import { SavedObjectsClientContract, } from 'src/core/server'; import Boom from 'boom'; +import LRU from 'lru-cache'; import { Agent, AgentAction, + AgentPolicyAction, AgentEvent, AgentEventSOAttributes, AgentSOAttributes, AgentActionSOAttributes, - FullAgentPolicy, } from '../../types'; import { AGENT_EVENT_SAVED_OBJECT_TYPE, @@ -30,11 +31,20 @@ import { forceUnenrollAgent } from './unenroll'; const ALLOWED_ACKNOWLEDGEMENT_TYPE: string[] = ['ACTION_RESULT']; +const actionCache = new LRU({ + max: 20, + maxAge: 10 * 60 * 1000, // 10 minutes +}); + export async function acknowledgeAgentActions( soClient: SavedObjectsClientContract, agent: Agent, agentEvents: AgentEvent[] ): Promise { + if (agentEvents.length === 0) { + return []; + } + for (const agentEvent of agentEvents) { if (!isAllowedType(agentEvent.type)) { throw Boom.badRequest(`${agentEvent.type} not allowed for acknowledgment only ACTION_RESULT`); @@ -45,9 +55,9 @@ export async function acknowledgeAgentActions( .map((event) => event.action_id) .filter((actionId) => actionId !== undefined) as string[]; - let actions; + let actions: AgentAction[]; try { - actions = await getAgentActionByIds(soClient, actionIds); + actions = await fetchActionsUsingCache(soClient, actionIds); } catch (error) { if (Boom.isBoom(error) && error.output.statusCode === 404) { throw Boom.badRequest(`One or more actions cannot be found`); @@ -55,65 +65,91 @@ export async function acknowledgeAgentActions( throw error; } + const agentActionsIds: string[] = []; for (const action of actions) { - if (action.agent_id !== agent.id) { + if (action.agent_id) { + agentActionsIds.push(action.id); + } + if (action.agent_id && action.agent_id !== agent.id) { throw Boom.badRequest(`${action.id} not found`); } } - if (actions.length === 0) { - return []; - } - const isAgentUnenrolled = actions.some((action) => action.type === 'UNENROLL'); if (isAgentUnenrolled) { await forceUnenrollAgent(soClient, agent.id); } - const agentPolicy = getLatestAgentPolicyIfUpdated(agent, actions); + const configChangeAction = getLatestConfigChangePolicyActionIfUpdated(agent, actions); await soClient.bulkUpdate([ - ...(agentPolicy ? [buildUpdateAgentPolicy(agent.id, agentPolicy)] : []), - ...buildUpdateAgentActionSentAt(actionIds), + ...(configChangeAction + ? [ + { + type: AGENT_SAVED_OBJECT_TYPE, + id: agent.id, + attributes: { + policy_revision: configChangeAction.policy_revision, + packages: configChangeAction?.ack_data?.packages, + }, + }, + ] + : []), + ...buildUpdateAgentActionSentAt(agentActionsIds), ]); return actions; } -function getLatestAgentPolicyIfUpdated(agent: Agent, actions: AgentAction[]) { - return actions.reduce((acc, action) => { - if (action.type !== 'CONFIG_CHANGE') { - return acc; - } - const data = action.data || {}; +async function fetchActionsUsingCache( + soClient: SavedObjectsClientContract, + actionIds: string[] +): Promise { + const missingActionIds: string[] = []; + const actions = actionIds + .map((actionId) => { + const action = actionCache.get(actionId); + if (!action) { + missingActionIds.push(actionId); + } + return action; + }) + .filter((action): action is AgentAction => action !== undefined); + + if (missingActionIds.length === 0) { + return actions; + } - if (data?.config?.id !== agent.policy_id) { - return acc; - } + const freshActions = await getAgentActionByIds(soClient, actionIds, false); + freshActions.forEach((action) => actionCache.set(action.id, action)); - const currentRevision = (acc && acc.revision) || agent.policy_revision || 0; + return [...freshActions, ...actions]; +} - return data?.config?.revision > currentRevision ? data?.config : acc; - }, null); +function isAgentPolicyAction(action: AgentAction | AgentPolicyAction): action is AgentPolicyAction { + return (action as AgentPolicyAction).policy_id !== undefined; } -function buildUpdateAgentPolicy(agentId: string, agentPolicy: FullAgentPolicy) { - const packages = agentPolicy.inputs.reduce((acc, input) => { - const packageName = input.meta?.package?.name; - if (packageName && acc.indexOf(packageName) < 0) { - return [packageName, ...acc]; +function getLatestConfigChangePolicyActionIfUpdated( + agent: Agent, + actions: Array +): AgentPolicyAction | null { + return actions.reduce((acc, action) => { + if ( + !isAgentPolicyAction(action) || + action.type !== 'CONFIG_CHANGE' || + action.policy_id !== agent.policy_id || + (acc?.policy_revision ?? 0) < (agent.policy_revision || 0) + ) { + return acc; } - return acc; - }, []); - return { - type: AGENT_SAVED_OBJECT_TYPE, - id: agentId, - attributes: { - policy_revision: agentPolicy.revision, - packages, - }, - }; + if (action.policy_revision > (acc?.policy_revision ?? 0)) { + return action; + } + + return acc; + }, null); } function buildUpdateAgentActionSentAt( diff --git a/x-pack/plugins/ingest_manager/server/services/agents/actions.test.ts b/x-pack/plugins/ingest_manager/server/services/agents/actions.test.ts index c739007952389..bcb3fc7fdc7bd 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/actions.test.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/actions.test.ts @@ -22,7 +22,13 @@ describe('test agent actions services', () => { }; mockSavedObjectsClient.create.mockReturnValue( Promise.resolve({ - attributes: {}, + attributes: { + agent_id: 'agentid', + type: 'CONFIG_CHANGE', + data: JSON.stringify({ content: 'data' }), + sent_at: '2020-03-14T19:45:02.620Z', + created_at: '2020-03-14T19:45:02.620Z', + }, } as SavedObject) ); await createAgentAction(mockSavedObjectsClient, newAgentAction); diff --git a/x-pack/plugins/ingest_manager/server/services/agents/actions.ts b/x-pack/plugins/ingest_manager/server/services/agents/actions.ts index cd0dd92131230..8519714334986 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/actions.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/actions.ts @@ -5,9 +5,20 @@ */ import { SavedObjectsClientContract } from 'kibana/server'; -import { Agent, AgentAction, AgentActionSOAttributes } from '../../../common/types/models'; +import { + Agent, + AgentAction, + AgentPolicyAction, + BaseAgentActionSOAttributes, + AgentActionSOAttributes, + AgentPolicyActionSOAttributes, +} from '../../../common/types/models'; import { AGENT_ACTION_SAVED_OBJECT_TYPE } from '../../../common/constants'; -import { savedObjectToAgentAction } from './saved_objects'; +import { + isAgentActionSavedObject, + isPolicyActionSavedObject, + savedObjectToAgentAction, +} from './saved_objects'; import { appContextService } from '../app_context'; import { nodeTypes } from '../../../../../../src/plugins/data/common'; @@ -15,15 +26,45 @@ export async function createAgentAction( soClient: SavedObjectsClientContract, newAgentAction: Omit ): Promise { - const so = await soClient.create(AGENT_ACTION_SAVED_OBJECT_TYPE, { + return createAction(soClient, newAgentAction); +} + +export function createAgentPolicyAction( + soClient: SavedObjectsClientContract, + newAgentAction: Omit +): Promise { + return createAction(soClient, newAgentAction); +} +async function createAction( + soClient: SavedObjectsClientContract, + newAgentAction: Omit +): Promise; +async function createAction( + soClient: SavedObjectsClientContract, + newAgentAction: Omit +): Promise; +async function createAction( + soClient: SavedObjectsClientContract, + newAgentAction: Omit | Omit +): Promise { + const so = await soClient.create(AGENT_ACTION_SAVED_OBJECT_TYPE, { ...newAgentAction, data: newAgentAction.data ? JSON.stringify(newAgentAction.data) : undefined, + ack_data: newAgentAction.ack_data ? JSON.stringify(newAgentAction.ack_data) : undefined, }); - const agentAction = savedObjectToAgentAction(so); - agentAction.data = newAgentAction.data; + if (isAgentActionSavedObject(so)) { + const agentAction = savedObjectToAgentAction(so); + agentAction.data = newAgentAction.data; + + return agentAction; + } else if (isPolicyActionSavedObject(so)) { + const agentAction = savedObjectToAgentAction(so); + agentAction.data = newAgentAction.data; - return agentAction; + return agentAction; + } + throw new Error('Invalid action'); } export async function getAgentActionsForCheckin( @@ -67,7 +108,8 @@ export async function getAgentActionsForCheckin( export async function getAgentActionByIds( soClient: SavedObjectsClientContract, - actionIds: string[] + actionIds: string[], + decryptData: boolean = true ) { const actions = ( await soClient.bulkGet( @@ -76,7 +118,11 @@ export async function getAgentActionByIds( type: AGENT_ACTION_SAVED_OBJECT_TYPE, })) ) - ).saved_objects.map(savedObjectToAgentAction); + ).saved_objects.map((action) => savedObjectToAgentAction(action)); + + if (!decryptData) { + return actions; + } return Promise.all( actions.map(async (action) => { @@ -93,6 +139,39 @@ export async function getAgentActionByIds( ); } +export async function getAgentPolicyActionByIds( + soClient: SavedObjectsClientContract, + actionIds: string[], + decryptData: boolean = true +) { + const actions = ( + await soClient.bulkGet( + actionIds.map((actionId) => ({ + id: actionId, + type: AGENT_ACTION_SAVED_OBJECT_TYPE, + })) + ) + ).saved_objects.map((action) => savedObjectToAgentAction(action)); + + if (!decryptData) { + return actions; + } + + return Promise.all( + actions.map(async (action) => { + // Get decrypted actions + return savedObjectToAgentAction( + await appContextService + .getEncryptedSavedObjects() + .getDecryptedAsInternalUser( + AGENT_ACTION_SAVED_OBJECT_TYPE, + action.id + ) + ); + }) + ); +} + export async function getNewActionsSince(soClient: SavedObjectsClientContract, timestamp: string) { const filter = nodeTypes.function.buildNode('and', [ nodeTypes.function.buildNode( @@ -116,7 +195,26 @@ export async function getNewActionsSince(soClient: SavedObjectsClientContract, t filter, }); - return res.saved_objects.map(savedObjectToAgentAction); + return res.saved_objects + .filter(isAgentActionSavedObject) + .map((so) => savedObjectToAgentAction(so)); +} + +export async function getLatestConfigChangeAction( + soClient: SavedObjectsClientContract, + policyId: string +) { + const res = await soClient.find({ + type: AGENT_ACTION_SAVED_OBJECT_TYPE, + search: policyId, + searchFields: ['policy_id'], + sortField: 'created_at', + sortOrder: 'DESC', + }); + + if (res.saved_objects[0]) { + return savedObjectToAgentAction(res.saved_objects[0]); + } } export interface ActionsService { @@ -124,6 +222,6 @@ export interface ActionsService { createAgentAction: ( soClient: SavedObjectsClientContract, - newAgentAction: AgentActionSOAttributes + newAgentAction: Omit ) => Promise; } diff --git a/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts b/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts index eddfb0e64b84b..8f586420c3ecb 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts @@ -5,6 +5,7 @@ */ import { timer, from, Observable, TimeoutError } from 'rxjs'; +import { omit } from 'lodash'; import { shareReplay, distinctUntilKeyChanged, @@ -16,14 +17,7 @@ import { take, } from 'rxjs/operators'; import { SavedObjectsClientContract, KibanaRequest } from 'src/core/server'; -import { - Agent, - AgentAction, - AgentSOAttributes, - AgentPolicy, - FullAgentPolicy, -} from '../../../types'; -import { agentPolicyService } from '../../agent_policy'; +import { Agent, AgentAction, AgentPolicyAction, AgentSOAttributes } from '../../../types'; import * as APIKeysService from '../../api_keys'; import { AGENT_SAVED_OBJECT_TYPE, @@ -31,7 +25,11 @@ import { AGENT_POLICY_ROLLOUT_RATE_LIMIT_INTERVAL_MS, AGENT_POLICY_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL, } from '../../../constants'; -import { createAgentAction, getNewActionsSince } from '../actions'; +import { + getNewActionsSince, + getLatestConfigChangeAction, + getAgentPolicyActionByIds, +} from '../actions'; import { appContextService } from '../../app_context'; import { toPromiseAbortable, AbortError, createRateLimiter } from './rxjs_utils'; @@ -54,27 +52,27 @@ function getInternalUserSOClient() { return appContextService.getInternalUserSOClient(fakeRequest); } -function createAgentPolicySharedObservable(agentPolicyId: string) { +function createNewActionsSharedObservable(): Observable { const internalSOClient = getInternalUserSOClient(); + return timer(0, AGENT_UPDATE_ACTIONS_INTERVAL_MS).pipe( - switchMap(() => - from(agentPolicyService.get(internalSOClient, agentPolicyId) as Promise) - ), - distinctUntilKeyChanged('revision'), - switchMap((data) => - from(agentPolicyService.getFullAgentPolicy(internalSOClient, agentPolicyId)) - ), + switchMap(() => { + return from(getNewActionsSince(internalSOClient, new Date().toISOString())); + }), shareReplay({ refCount: true, bufferSize: 1 }) ); } -function createNewActionsSharedObservable(): Observable { - return timer(0, AGENT_UPDATE_ACTIONS_INTERVAL_MS).pipe( - switchMap(() => { - const internalSOClient = getInternalUserSOClient(); +function createAgentPolicyActionSharedObservable(agentPolicyId: string) { + const internalSOClient = getInternalUserSOClient(); - return from(getNewActionsSince(internalSOClient, new Date().toISOString())); - }), + return timer(0, AGENT_UPDATE_ACTIONS_INTERVAL_MS).pipe( + switchMap(() => from(getLatestConfigChangeAction(internalSOClient, agentPolicyId))), + filter((data): data is AgentPolicyAction => data !== undefined), + distinctUntilKeyChanged('id'), + switchMap((data) => + from(getAgentPolicyActionByIds(internalSOClient, [data.id]).then((r) => r[0])) + ), shareReplay({ refCount: true, bufferSize: 1 }) ); } @@ -102,47 +100,35 @@ async function getOrCreateAgentDefaultOutputAPIKey( return outputAPIKey.key; } -function shouldCreateAgentPolicyAction(agent: Agent, agentPolicy: FullAgentPolicy | null): boolean { - if (!agentPolicy || !agentPolicy.revision) { - return false; - } - const isAgentPolicyOutdated = - !agent.policy_revision || agent.policy_revision < agentPolicy.revision; - if (!isAgentPolicyOutdated) { - return false; - } - - return true; -} - -async function createAgentActionFromAgentPolicy( +async function createAgentActionFromPolicyAction( soClient: SavedObjectsClientContract, agent: Agent, - policy: FullAgentPolicy | null + policyAction: AgentPolicyAction ) { - // Deep clone !not supporting Date, and undefined value. - const newAgentPolicy = JSON.parse(JSON.stringify(policy)); + const newAgentAction: AgentAction = Object.assign( + omit( + // Faster than clone + JSON.parse(JSON.stringify(policyAction)) as AgentPolicyAction, + 'policy_id', + 'policy_revision' + ), + { + agent_id: agent.id, + } + ); // Mutate the policy to set the api token for this agent - newAgentPolicy.outputs.default.api_key = await getOrCreateAgentDefaultOutputAPIKey( + newAgentAction.data.config.outputs.default.api_key = await getOrCreateAgentDefaultOutputAPIKey( soClient, agent ); - const policyChangeAction = await createAgentAction(soClient, { - agent_id: agent.id, - type: 'CONFIG_CHANGE', - data: { config: newAgentPolicy } as any, - created_at: new Date().toISOString(), - sent_at: undefined, - }); - - return [policyChangeAction]; + return [newAgentAction]; } export function agentCheckinStateNewActionsFactory() { // Shared Observables - const agentPolicies$ = new Map>(); + const agentPolicies$ = new Map>(); const newActions$ = createNewActionsSharedObservable(); // Rx operators const rateLimiter = createRateLimiter( @@ -162,7 +148,7 @@ export function agentCheckinStateNewActionsFactory() { } const agentPolicyId = agent.policy_id; if (!agentPolicies$.has(agentPolicyId)) { - agentPolicies$.set(agentPolicyId, createAgentPolicySharedObservable(agentPolicyId)); + agentPolicies$.set(agentPolicyId, createAgentPolicyActionSharedObservable(agentPolicyId)); } const agentPolicy$ = agentPolicies$.get(agentPolicyId); if (!agentPolicy$) { @@ -174,15 +160,22 @@ export function agentCheckinStateNewActionsFactory() { // Set a timeout 3s before the real timeout to have a chance to respond an empty response before socket timeout Math.max((appContextService.getConfig()?.fleet.pollingRequestTimeout ?? 0) - 3000, 3000) ), - filter((agentPolicy) => shouldCreateAgentPolicyAction(agent, agentPolicy)), + filter( + (action) => + agent.policy_id !== undefined && + action.policy_revision !== undefined && + action.policy_id !== undefined && + action.policy_id === agent.policy_id && + (!agent.policy_revision || action.policy_revision > agent.policy_revision) + ), rateLimiter(), - mergeMap((agentPolicy) => createAgentActionFromAgentPolicy(soClient, agent, agentPolicy)), + mergeMap((policyAction) => createAgentActionFromPolicyAction(soClient, agent, policyAction)), merge(newActions$), mergeMap(async (data) => { if (!data) { return; } - const newActions = data.filter((action) => action.agent_id); + const newActions = data.filter((action) => action.agent_id === agent.id); if (newActions.length === 0) { return; } diff --git a/x-pack/plugins/ingest_manager/server/services/agents/saved_objects.ts b/x-pack/plugins/ingest_manager/server/services/agents/saved_objects.ts index 2ab5cc8139f69..3ae664c086da9 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/saved_objects.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/saved_objects.ts @@ -6,7 +6,15 @@ import Boom from 'boom'; import { SavedObject } from 'src/core/server'; -import { Agent, AgentSOAttributes, AgentAction, AgentActionSOAttributes } from '../../types'; +import { + Agent, + AgentSOAttributes, + AgentAction, + AgentPolicyAction, + AgentActionSOAttributes, + AgentPolicyActionSOAttributes, + BaseAgentActionSOAttributes, +} from '../../types'; export function savedObjectToAgent(so: SavedObject): Agent { if (so.error) { @@ -27,7 +35,13 @@ export function savedObjectToAgent(so: SavedObject): Agent { }; } -export function savedObjectToAgentAction(so: SavedObject): AgentAction { +export function savedObjectToAgentAction(so: SavedObject): AgentAction; +export function savedObjectToAgentAction( + so: SavedObject +): AgentPolicyAction; +export function savedObjectToAgentAction( + so: SavedObject +): AgentAction | AgentPolicyAction { if (so.error) { if (so.error.statusCode === 404) { throw Boom.notFound(so.error.message); @@ -36,9 +50,42 @@ export function savedObjectToAgentAction(so: SavedObject +): so is SavedObject { + return (so.attributes as AgentActionSOAttributes).agent_id !== undefined; +} + +export function isPolicyActionSavedObject( + so: SavedObject +): so is SavedObject { + return (so.attributes as AgentPolicyActionSOAttributes).policy_id !== undefined; +} diff --git a/x-pack/plugins/ingest_manager/server/services/setup.ts b/x-pack/plugins/ingest_manager/server/services/setup.ts index ec3a05a4fa390..f02057bae1598 100644 --- a/x-pack/plugins/ingest_manager/server/services/setup.ts +++ b/x-pack/plugins/ingest_manager/server/services/setup.ts @@ -170,6 +170,12 @@ export async function setupFleet( }); }) ); + + await Promise.all( + agentPolicies.map((agentPolicy) => + agentPolicyService.createFleetPolicyChangeAction(soClient, agentPolicy.id) + ) + ); } function generateRandomPassword() { diff --git a/x-pack/plugins/ingest_manager/server/types/index.tsx b/x-pack/plugins/ingest_manager/server/types/index.tsx index 2746dfcd00ce3..d00491afef72b 100644 --- a/x-pack/plugins/ingest_manager/server/types/index.tsx +++ b/x-pack/plugins/ingest_manager/server/types/index.tsx @@ -16,7 +16,10 @@ export { AgentEvent, AgentEventSOAttributes, AgentAction, + AgentPolicyAction, + BaseAgentActionSOAttributes, AgentActionSOAttributes, + AgentPolicyActionSOAttributes, PackagePolicy, PackagePolicyInput, PackagePolicyInputStream, diff --git a/x-pack/plugins/ingest_manager/server/types/models/agent.ts b/x-pack/plugins/ingest_manager/server/types/models/agent.ts index 5ad98cfd40622..b249705fe6c2f 100644 --- a/x-pack/plugins/ingest_manager/server/types/models/agent.ts +++ b/x-pack/plugins/ingest_manager/server/types/models/agent.ts @@ -62,12 +62,7 @@ export const AgentEventSchema = schema.object({ }); export const NewAgentActionSchema = schema.object({ - type: schema.oneOf([ - schema.literal('CONFIG_CHANGE'), - schema.literal('DATA_DUMP'), - schema.literal('RESUME'), - schema.literal('PAUSE'), - ]), + type: schema.oneOf([schema.literal('CONFIG_CHANGE'), schema.literal('UNENROLL')]), data: schema.maybe(schema.any()), sent_at: schema.maybe(schema.string()), }); diff --git a/x-pack/plugins/lens/kibana.json b/x-pack/plugins/lens/kibana.json index b8747fc1f0cde..67d9d5ef64483 100644 --- a/x-pack/plugins/lens/kibana.json +++ b/x-pack/plugins/lens/kibana.json @@ -8,7 +8,7 @@ "data", "expressions", "navigation", - "kibanaLegacy", + "urlForwarding", "visualizations", "dashboard", "charts" diff --git a/x-pack/plugins/lens/public/plugin.ts b/x-pack/plugins/lens/public/plugin.ts index a767f2a17fb69..f9c63f54d6713 100644 --- a/x-pack/plugins/lens/public/plugin.ts +++ b/x-pack/plugins/lens/public/plugin.ts @@ -10,7 +10,7 @@ import { EmbeddableSetup, EmbeddableStart } from 'src/plugins/embeddable/public' import { ExpressionsSetup, ExpressionsStart } from 'src/plugins/expressions/public'; import { VisualizationsSetup } from 'src/plugins/visualizations/public'; import { NavigationPublicPluginStart } from 'src/plugins/navigation/public'; -import { KibanaLegacySetup } from 'src/plugins/kibana_legacy/public'; +import { UrlForwardingSetup } from 'src/plugins/url_forwarding/public'; import { ChartsPluginSetup } from '../../../../src/plugins/charts/public'; import { EditorFrameService } from './editor_frame_service'; import { @@ -35,7 +35,7 @@ import { getLensAliasConfig } from './vis_type_alias'; import './index.scss'; export interface LensPluginSetupDependencies { - kibanaLegacy: KibanaLegacySetup; + urlForwarding: UrlForwardingSetup; expressions: ExpressionsSetup; data: DataPublicPluginSetup; embeddable?: EmbeddableSetup; @@ -72,7 +72,7 @@ export class LensPlugin { setup( core: CoreSetup, { - kibanaLegacy, + urlForwarding, expressions, data, embeddable, @@ -116,7 +116,7 @@ export class LensPlugin { }, }); - kibanaLegacy.forwardApp('lens', 'lens'); + urlForwarding.forwardApp('lens', 'lens'); } start(core: CoreStart, startDependencies: LensPluginStartDependencies) { diff --git a/x-pack/plugins/ml/common/types/data_frame_analytics.ts b/x-pack/plugins/ml/common/types/data_frame_analytics.ts index 60d2ca63dda59..96d6c81a3d309 100644 --- a/x-pack/plugins/ml/common/types/data_frame_analytics.ts +++ b/x-pack/plugins/ml/common/types/data_frame_analytics.ts @@ -4,11 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import { CustomHttpResponseOptions, ResponseError } from 'kibana/server'; +import Boom from 'boom'; +import { EsErrorBody } from '../util/errors'; export interface DeleteDataFrameAnalyticsWithIndexStatus { success: boolean; - error?: CustomHttpResponseOptions; + error?: EsErrorBody | Boom; } export type IndexName = string; diff --git a/x-pack/plugins/ml/common/util/errors.test.ts b/x-pack/plugins/ml/common/util/errors.test.ts deleted file mode 100644 index 0b99799e3b6ec..0000000000000 --- a/x-pack/plugins/ml/common/util/errors.test.ts +++ /dev/null @@ -1,80 +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 { - BoomResponse, - extractErrorMessage, - MLCustomHttpResponseOptions, - MLResponseError, -} from './errors'; -import { ResponseError } from 'kibana/server'; - -describe('ML - error message utils', () => { - describe('extractErrorMessage', () => { - test('returns just the error message', () => { - const testMsg = 'Saved object [index-pattern/blahblahblah] not found'; - - const bodyWithNestedErrorMsg: MLCustomHttpResponseOptions = { - body: { - message: { - msg: testMsg, - }, - }, - statusCode: 404, - }; - expect(extractErrorMessage(bodyWithNestedErrorMsg)).toBe(testMsg); - - const bodyWithStringMsg: MLCustomHttpResponseOptions = { - body: { - msg: testMsg, - statusCode: 404, - response: `{"error":{"reason":"${testMsg}"}}`, - }, - statusCode: 404, - }; - expect(extractErrorMessage(bodyWithStringMsg)).toBe(testMsg); - - const bodyWithStringMessage: MLCustomHttpResponseOptions = { - body: { - message: testMsg, - }, - statusCode: 404, - }; - expect(extractErrorMessage(bodyWithStringMessage)).toBe(testMsg); - - const bodyWithString: MLCustomHttpResponseOptions = { - body: testMsg, - statusCode: 404, - }; - expect(extractErrorMessage(bodyWithString)).toBe(testMsg); - - const bodyWithError: MLCustomHttpResponseOptions = { - body: new Error(testMsg), - statusCode: 404, - }; - expect(extractErrorMessage(bodyWithError)).toBe(testMsg); - - const bodyWithBoomError: MLCustomHttpResponseOptions = { - statusCode: 404, - body: { - data: [], - isBoom: true, - isServer: false, - output: { - statusCode: 404, - payload: { - statusCode: 404, - error: testMsg, - message: testMsg, - }, - headers: {}, - }, - }, - }; - expect(extractErrorMessage(bodyWithBoomError)).toBe(testMsg); - }); - }); -}); diff --git a/x-pack/plugins/ml/common/util/errors.ts b/x-pack/plugins/ml/common/util/errors.ts deleted file mode 100644 index a5f89db96cfd7..0000000000000 --- a/x-pack/plugins/ml/common/util/errors.ts +++ /dev/null @@ -1,177 +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 { ResponseError, ResponseHeaders } from 'kibana/server'; -import { isErrorResponse } from '../types/errors'; - -export function getErrorMessage(error: any) { - if (isErrorResponse(error)) { - return `${error.body.error}: ${error.body.message}`; - } - - if (typeof error === 'object' && typeof error.message === 'string') { - return error.message; - } - - return JSON.stringify(error); -} - -// Adding temporary types until Kibana ResponseError is updated - -export interface BoomResponse { - data: any; - isBoom: boolean; - isServer: boolean; - output: { - statusCode: number; - payload: { - statusCode: number; - error: string; - message: string; - }; - headers: {}; - }; -} -export type MLResponseError = - | { - message: { - msg: string; - }; - } - | { msg: string; statusCode: number; response: string }; - -export interface MLCustomHttpResponseOptions< - T extends ResponseError | MLResponseError | BoomResponse -> { - /** HTTP message to send to the client */ - body?: T; - /** HTTP Headers with additional information about response */ - headers?: ResponseHeaders; - statusCode: number; -} - -export interface MLErrorObject { - message: string; - fullErrorMessage?: string; // For use in a 'See full error' popover. - statusCode?: number; -} - -export const extractErrorProperties = ( - error: - | MLCustomHttpResponseOptions - | string - | undefined -): MLErrorObject => { - // extract properties of the error object from within the response error - // coming from Kibana, Elasticsearch, and our own ML messages - let message = ''; - let fullErrorMessage; - let statusCode; - - if (typeof error === 'string') { - return { - message: error, - }; - } - if (error?.body === undefined) { - return { - message: '', - }; - } - - if (typeof error.body === 'string') { - return { - message: error.body, - }; - } - if ( - typeof error.body === 'object' && - 'output' in error.body && - error.body.output.payload.message - ) { - return { - message: error.body.output.payload.message, - }; - } - - if ( - typeof error.body === 'object' && - 'response' in error.body && - typeof error.body.response === 'string' - ) { - const errorResponse = JSON.parse(error.body.response); - if ('error' in errorResponse && typeof errorResponse === 'object') { - const errorResponseError = errorResponse.error; - if ('reason' in errorResponseError) { - message = errorResponseError.reason; - } - if ('caused_by' in errorResponseError) { - const causedByMessage = JSON.stringify(errorResponseError.caused_by); - // Only add a fullErrorMessage if different to the message. - if (causedByMessage !== message) { - fullErrorMessage = causedByMessage; - } - } - return { - message, - fullErrorMessage, - statusCode: error.statusCode, - }; - } - } - - if (typeof error.body === 'object' && 'msg' in error.body && typeof error.body.msg === 'string') { - return { - message: error.body.msg, - }; - } - - if (typeof error.body === 'object' && 'message' in error.body) { - if ( - 'attributes' in error.body && - typeof error.body.attributes === 'object' && - error.body.attributes.body?.status !== undefined - ) { - statusCode = error.body.attributes.body.status; - - if (typeof error.body.attributes.body.error?.reason === 'string') { - return { - message: error.body.attributes.body.error.reason, - statusCode, - }; - } - } - - if (typeof error.body.message === 'string') { - return { - message: error.body.message, - statusCode, - }; - } - if (!(error.body.message instanceof Error) && typeof (error.body.message.msg === 'string')) { - return { - message: error.body.message.msg, - statusCode, - }; - } - } - - // If all else fail return an empty message instead of JSON.stringify - return { - message: '', - }; -}; - -export const extractErrorMessage = ( - error: - | MLCustomHttpResponseOptions - | undefined - | string -): string => { - // extract only the error message within the response error coming from Kibana, Elasticsearch, and our own ML messages - const errorObj = extractErrorProperties(error); - return errorObj.message; -}; diff --git a/x-pack/plugins/ml/common/util/errors/errors.test.ts b/x-pack/plugins/ml/common/util/errors/errors.test.ts new file mode 100644 index 0000000000000..ddaf0b04dd12b --- /dev/null +++ b/x-pack/plugins/ml/common/util/errors/errors.test.ts @@ -0,0 +1,99 @@ +/* + * 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 'boom'; + +import { extractErrorMessage, MLHttpFetchError, MLResponseError, EsErrorBody } from './index'; + +describe('ML - error message utils', () => { + describe('extractErrorMessage', () => { + test('returns just the error message', () => { + const testMsg = 'Saved object [index-pattern/indexpattern] not found'; + + // bad error, return empty string + const badError = {} as any; + expect(extractErrorMessage(badError)).toBe(''); + + // raw es error + const esErrorMsg: EsErrorBody = { + error: { + root_cause: [ + { + type: 'type', + reason: 'reason', + }, + ], + type: 'type', + reason: testMsg, + }, + status: 404, + }; + expect(extractErrorMessage(esErrorMsg)).toBe(testMsg); + + // error is basic string + const stringMessage = testMsg; + expect(extractErrorMessage(stringMessage)).toBe(testMsg); + + // kibana error without attributes + const bodyWithoutAttributes: MLHttpFetchError = { + name: 'name', + req: {} as Request, + request: {} as Request, + message: 'Something else', + body: { + statusCode: 404, + error: 'error', + message: testMsg, + }, + }; + expect(extractErrorMessage(bodyWithoutAttributes)).toBe(testMsg); + + // kibana error with attributes + const bodyWithAttributes: MLHttpFetchError = { + name: 'name', + req: {} as Request, + request: {} as Request, + message: 'Something else', + body: { + statusCode: 404, + error: 'error', + message: 'Something else', + attributes: { + body: { + status: 404, + error: { + reason: testMsg, + type: 'type', + root_cause: [{ type: 'type', reason: 'reason' }], + }, + }, + }, + }, + }; + expect(extractErrorMessage(bodyWithAttributes)).toBe(testMsg); + + // boom error + const boomError: Boom = { + message: '', + reformat: () => '', + name: '', + data: [], + isBoom: true, + isServer: false, + output: { + statusCode: 404, + payload: { + statusCode: 404, + error: testMsg, + message: testMsg, + }, + headers: {}, + }, + }; + expect(extractErrorMessage(boomError)).toBe(testMsg); + }); + }); +}); diff --git a/x-pack/plugins/ml/common/util/errors/index.ts b/x-pack/plugins/ml/common/util/errors/index.ts new file mode 100644 index 0000000000000..d6d33b86e6fa9 --- /dev/null +++ b/x-pack/plugins/ml/common/util/errors/index.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. + */ + +export { MLRequestFailure } from './request_error'; +export { extractErrorMessage, extractErrorProperties } from './process_errors'; +export { + ErrorType, + EsErrorBody, + EsErrorRootCause, + MLErrorObject, + MLHttpFetchError, + MLResponseError, + isBoomError, + isErrorString, + isEsErrorBody, + isMLResponseError, +} from './types'; diff --git a/x-pack/plugins/ml/common/util/errors/process_errors.ts b/x-pack/plugins/ml/common/util/errors/process_errors.ts new file mode 100644 index 0000000000000..4addfa414ef56 --- /dev/null +++ b/x-pack/plugins/ml/common/util/errors/process_errors.ts @@ -0,0 +1,83 @@ +/* + * 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 { + ErrorType, + MLErrorObject, + isBoomError, + isErrorString, + isEsErrorBody, + isMLResponseError, +} from './types'; + +export const extractErrorProperties = (error: ErrorType): MLErrorObject => { + // extract properties of the error object from within the response error + // coming from Kibana, Elasticsearch, and our own ML messages + + // some responses contain raw es errors as part of a bulk response + // e.g. if some jobs fail the action in a bulk request + if (isEsErrorBody(error)) { + return { + message: error.error.reason, + statusCode: error.status, + fullError: error, + }; + } + + if (isErrorString(error)) { + return { + message: error, + }; + } + + if (isBoomError(error)) { + return { + message: error.output.payload.message, + statusCode: error.output.payload.statusCode, + }; + } + + if (error?.body === undefined) { + return { + message: '', + }; + } + + if (typeof error.body === 'string') { + return { + message: error.body, + }; + } + + if (isMLResponseError(error)) { + if ( + typeof error.body.attributes === 'object' && + typeof error.body.attributes.body?.error?.reason === 'string' + ) { + return { + message: error.body.attributes.body.error.reason, + statusCode: error.body.statusCode, + fullError: error.body.attributes.body, + }; + } else { + return { + message: error.body.message, + statusCode: error.body.statusCode, + }; + } + } + + // If all else fail return an empty message instead of JSON.stringify + return { + message: '', + }; +}; + +export const extractErrorMessage = (error: ErrorType): string => { + // extract only the error message within the response error coming from Kibana, Elasticsearch, and our own ML messages + const errorObj = extractErrorProperties(error); + return errorObj.message; +}; diff --git a/x-pack/plugins/ml/common/util/errors/request_error.ts b/x-pack/plugins/ml/common/util/errors/request_error.ts new file mode 100644 index 0000000000000..faa8a8e2dc0d4 --- /dev/null +++ b/x-pack/plugins/ml/common/util/errors/request_error.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 { MLErrorObject, ErrorType } from './types'; + +export class MLRequestFailure extends Error { + constructor(error: MLErrorObject, resp: ErrorType) { + super(error.message); + Object.setPrototypeOf(this, new.target.prototype); + + if (typeof resp !== 'string' && typeof resp !== 'undefined') { + if ('body' in resp) { + this.stack = JSON.stringify(resp.body, null, 2); + } else { + try { + this.stack = JSON.stringify(resp, null, 2); + } catch (e) { + // fail silently + } + } + } + } +} diff --git a/x-pack/plugins/ml/common/util/errors/types.ts b/x-pack/plugins/ml/common/util/errors/types.ts new file mode 100644 index 0000000000000..3d9fc82be8d85 --- /dev/null +++ b/x-pack/plugins/ml/common/util/errors/types.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 { HttpFetchError } from 'kibana/public'; +import Boom from 'boom'; + +export interface EsErrorRootCause { + type: string; + reason: string; +} + +export interface EsErrorBody { + error: { + root_cause?: EsErrorRootCause[]; + caused_by?: EsErrorRootCause; + type: string; + reason: string; + }; + status: number; +} + +export interface MLResponseError { + statusCode: number; + error: string; + message: string; + attributes?: { + body: EsErrorBody; + }; +} + +export interface MLErrorObject { + message: string; + statusCode?: number; + fullError?: EsErrorBody; +} + +export interface MLHttpFetchError extends HttpFetchError { + body: T; +} + +export type ErrorType = MLHttpFetchError | EsErrorBody | Boom | string | undefined; + +export function isEsErrorBody(error: any): error is EsErrorBody { + return error && error.error?.reason !== undefined; +} + +export function isErrorString(error: any): error is string { + return typeof error === 'string'; +} + +export function isMLResponseError(error: any): error is MLResponseError { + return typeof error.body === 'object' && 'message' in error.body; +} + +export function isBoomError(error: any): error is Boom { + return error.isBoom === true; +} diff --git a/x-pack/plugins/ml/public/application/components/messagebar/messagebar_service.d.ts b/x-pack/plugins/ml/public/application/components/messagebar/messagebar_service.d.ts deleted file mode 100644 index 29a537a7ca8d8..0000000000000 --- a/x-pack/plugins/ml/public/application/components/messagebar/messagebar_service.d.ts +++ /dev/null @@ -1,13 +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. - */ - -declare interface MlMessageBarService { - notify: { - error(text: any, resp?: any): void; - }; -} - -export const mlMessageBarService: MlMessageBarService; diff --git a/x-pack/plugins/ml/public/application/components/messagebar/messagebar_service.js b/x-pack/plugins/ml/public/application/components/messagebar/messagebar_service.js deleted file mode 100644 index 1dc7140bd2687..0000000000000 --- a/x-pack/plugins/ml/public/application/components/messagebar/messagebar_service.js +++ /dev/null @@ -1,33 +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 { getToastNotifications } from '../../util/dependency_cache'; -import { MLRequestFailure } from '../../util/ml_error'; -import { i18n } from '@kbn/i18n'; - -function errorNotify(text, resp) { - let err = null; - if (typeof text === 'object' && text.response !== undefined) { - resp = text.response; - } else if (typeof text === 'object' && text.message !== undefined) { - err = new Error(text.message); - } else { - err = new Error(text); - } - - const toastNotifications = getToastNotifications(); - toastNotifications.addError(new MLRequestFailure(err, resp), { - title: i18n.translate('xpack.ml.messagebarService.errorTitle', { - defaultMessage: 'An error has occurred', - }), - }); -} - -export const mlMessageBarService = { - notify: { - error: errorNotify, - }, -}; diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js index eed57aaf1b491..5b0224c8e9f0a 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js @@ -10,6 +10,8 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; import { EuiButton, @@ -51,8 +53,7 @@ import { getPartitioningFieldNames } from '../../../../common/util/job_utils'; import { withKibana } from '../../../../../../../src/plugins/kibana_react/public'; import { mlJobService } from '../../services/job_service'; import { ml } from '../../services/ml_api_service'; -import { i18n } from '@kbn/i18n'; -import { FormattedMessage } from '@kbn/i18n/react'; +import { extractErrorMessage } from '../../../../common/util/errors'; class RuleEditorFlyoutUI extends Component { static propTypes = { @@ -431,8 +432,8 @@ class RuleEditorFlyoutUI extends Component { values: { jobId }, } ); - if (error.message) { - errorMessage += ` : ${error.message}`; + if (error.error) { + errorMessage += ` : ${extractErrorMessage(error.error)}`; } toasts.addDanger(errorMessage); }); diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/utils.js b/x-pack/plugins/ml/public/application/components/rule_editor/utils.js index a697eed00fd66..6a8e20647cdbe 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/utils.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/utils.js @@ -146,22 +146,17 @@ export function updateJobRules(job, detectorIndex, rules) { } return new Promise((resolve, reject) => { - mlJobService - .updateJob(jobId, jobData) - .then((resp) => { - if (resp.success) { - // Refresh the job data in the job service before resolving. - mlJobService - .refreshJob(jobId) - .then(() => { - resolve({ success: true }); - }) - .catch((refreshResp) => { - reject(refreshResp); - }); - } else { - reject(resp); - } + ml.updateJob({ jobId: jobId, job: jobData }) + .then(() => { + // Refresh the job data in the job service before resolving. + mlJobService + .refreshJob(jobId) + .then(() => { + resolve({ success: true }); + }) + .catch((refreshResp) => { + reject(refreshResp); + }); }) .catch((resp) => { reject(resp); diff --git a/x-pack/plugins/ml/public/application/components/validate_job/__snapshots__/validate_job_view.test.js.snap b/x-pack/plugins/ml/public/application/components/validate_job/__snapshots__/validate_job_view.test.js.snap index cbbf84b9e51ec..f6a161cc01999 100644 --- a/x-pack/plugins/ml/public/application/components/validate_job/__snapshots__/validate_job_view.test.js.snap +++ b/x-pack/plugins/ml/public/application/components/validate_job/__snapshots__/validate_job_view.test.js.snap @@ -8,7 +8,7 @@ exports[`ValidateJob renders button and modal with a message 1`] = ` iconSide="right" iconType="questionInCircle" isDisabled={false} - isLoading={false} + isLoading={true} onClick={[Function]} size="s" > @@ -18,62 +18,6 @@ exports[`ValidateJob renders button and modal with a message 1`] = ` values={Object {}} /> - - } - > - - - - - - - - , - } - } - /> - - `; @@ -108,7 +52,7 @@ exports[`ValidateJob renders the button and modal with a success message 1`] = ` iconSide="right" iconType="questionInCircle" isDisabled={false} - isLoading={false} + isLoading={true} onClick={[Function]} size="s" > @@ -118,52 +62,6 @@ exports[`ValidateJob renders the button and modal with a success message 1`] = ` values={Object {}} /> - - } - > - - - - - - - - , - } - } - /> - - `; diff --git a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.d.ts b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.d.ts index 43e0a5f3eac78..35e4e189b4326 100644 --- a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.d.ts +++ b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.d.ts @@ -8,7 +8,7 @@ import { FC } from 'react'; declare const ValidateJob: FC<{ getJobConfig: any; getDuration: any; - mlJobService: any; + ml: any; embedded?: boolean; setIsValid?: (valid: boolean) => void; idFilterList?: string[]; diff --git a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js index dde6925631d3e..0c079bc11cffc 100644 --- a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js +++ b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js @@ -32,6 +32,8 @@ import { getDocLinks } from '../../util/dependency_cache'; import { VALIDATION_STATUS } from '../../../../common/constants/validation'; import { getMostSevereMessageStatus } from '../../../../common/util/validation_utils'; +import { toastNotificationServiceProvider } from '../../services/toast_notification_service'; +import { withKibana } from '../../../../../../../src/plugins/kibana_react/public'; const defaultIconType = 'questionInCircle'; const getDefaultState = () => ({ @@ -182,7 +184,7 @@ Modal.propType = { title: PropTypes.string, }; -export class ValidateJob extends Component { +export class ValidateJobUI extends Component { constructor(props) { super(props); this.state = getDefaultState(); @@ -209,25 +211,40 @@ export class ValidateJob extends Component { if (typeof job === 'object') { let shouldShowLoadingIndicator = true; - this.props.mlJobService.validateJob({ duration, fields, job }).then((data) => { - shouldShowLoadingIndicator = false; - this.setState({ - ...this.state, - ui: { - ...this.state.ui, - iconType: statusToEuiIconType(getMostSevereMessageStatus(data.messages)), - isLoading: false, - isModalVisible: true, - }, - data, - title: job.job_id, - }); - if (typeof this.props.setIsValid === 'function') { - this.props.setIsValid( - data.messages.some((m) => m.status === VALIDATION_STATUS.ERROR) === false + this.props.ml + .validateJob({ duration, fields, job }) + .then((messages) => { + shouldShowLoadingIndicator = false; + this.setState({ + ...this.state, + ui: { + ...this.state.ui, + iconType: statusToEuiIconType(getMostSevereMessageStatus(messages)), + isLoading: false, + isModalVisible: true, + }, + data: { + messages, + success: true, + }, + title: job.job_id, + }); + if (typeof this.props.setIsValid === 'function') { + this.props.setIsValid( + messages.some((m) => m.status === VALIDATION_STATUS.ERROR) === false + ); + } + }) + .catch((error) => { + const { toasts } = this.props.kibana.services.notifications; + const toastNotificationService = toastNotificationServiceProvider(toasts); + toastNotificationService.displayErrorToast( + error, + i18n.translate('xpack.ml.jobService.validateJobErrorTitle', { + defaultMessage: 'Job Validation Error', + }) ); - } - }); + }); // wait for 250ms before triggering the loading indicator // to avoid flickering when there's a loading time below @@ -335,15 +352,17 @@ export class ValidateJob extends Component { ); } } -ValidateJob.propTypes = { +ValidateJobUI.propTypes = { fields: PropTypes.object, fill: PropTypes.bool, getDuration: PropTypes.func, getJobConfig: PropTypes.func.isRequired, isCurrentJobConfig: PropTypes.bool, isDisabled: PropTypes.bool, - mlJobService: PropTypes.object.isRequired, + ml: PropTypes.object.isRequired, embedded: PropTypes.bool, setIsValid: PropTypes.func, idFilterList: PropTypes.array, }; + +export const ValidateJob = withKibana(ValidateJobUI); diff --git a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.test.js b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.test.js index cc8a5abb4e9ab..280dbd76d5487 100644 --- a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.test.js +++ b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.test.js @@ -16,6 +16,12 @@ jest.mock('../../util/dependency_cache', () => ({ }), })); +jest.mock('../../../../../../../src/plugins/kibana_react/public', () => ({ + withKibana: (comp) => { + return comp; + }, +})); + const job = { job_id: 'test-id', }; @@ -25,11 +31,16 @@ const getJobConfig = () => job; function prepareTest(messages) { const p = Promise.resolve(messages); - const mlJobService = { - validateJob: () => p, + const ml = { + validateJob: () => Promise.resolve(messages), + }; + const kibana = { + services: { + notifications: { toasts: { addDanger: jest.fn() } }, + }, }; - const component = ; + const component = ; const wrapper = shallowWithIntl(component); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts index 97098ea9e75c6..60681fb6e7bbe 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts @@ -10,7 +10,7 @@ import { distinctUntilChanged, filter } from 'rxjs/operators'; import { cloneDeep } from 'lodash'; import { ml } from '../../services/ml_api_service'; import { Dictionary } from '../../../../common/types/common'; -import { getErrorMessage } from '../../../../common/util/errors'; +import { extractErrorMessage } from '../../../../common/util/errors'; import { SavedSearchQuery } from '../../contexts/ml'; import { AnalysisConfig, @@ -486,7 +486,7 @@ export const loadEvalData = async ({ results.eval = evalResult; return results; } catch (e) { - results.error = getErrorMessage(e); + results.error = extractErrorMessage(e); return results; } }; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts index c162cb2754c10..53c0f02fd9a80 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getErrorMessage } from '../../../../common/util/errors'; +import { extractErrorMessage } from '../../../../common/util/errors'; import { EsSorting, SearchResponse7, UseDataGridReturnType } from '../../components/data_grid'; import { ml } from '../../services/ml_api_service'; @@ -62,7 +62,7 @@ export const getIndexData = async ( setTableItems(docs); setStatus(INDEX_STATUS.LOADED); } catch (e) { - setErrorMessage(getErrorMessage(e)); + setErrorMessage(extractErrorMessage(e)); setStatus(INDEX_STATUS.ERROR); } } diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts index fde1b26106508..b0e73edff7476 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts @@ -8,7 +8,7 @@ import { useEffect, useState } from 'react'; import { IndexPattern } from '../../../../../../../src/plugins/data/public'; -import { getErrorMessage } from '../../../../common/util/errors'; +import { extractErrorMessage } from '../../../../common/util/errors'; import { getIndexPatternIdFromName } from '../../util/index_utils'; import { ml } from '../../services/ml_api_service'; @@ -83,12 +83,12 @@ export const useResultsViewConfig = (jobId: string) => { setIsLoadingJobConfig(false); } } catch (e) { - setJobCapsServiceErrorMessage(getErrorMessage(e)); + setJobCapsServiceErrorMessage(extractErrorMessage(e)); setIsLoadingJobConfig(false); } } } catch (e) { - setJobConfigErrorMessage(getErrorMessage(e)); + setJobConfigErrorMessage(extractErrorMessage(e)); setIsLoadingJobConfig(false); } })(); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts index eab5165a42137..ea958c8c4a3a3 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts @@ -25,7 +25,7 @@ import { SearchResponse7, UseIndexDataReturnType, } from '../../../../components/data_grid'; -import { getErrorMessage } from '../../../../../../common/util/errors'; +import { extractErrorMessage } from '../../../../../../common/util/errors'; import { INDEX_STATUS } from '../../../common/analytics'; import { ml } from '../../../../services/ml_api_service'; @@ -94,7 +94,7 @@ export const useIndexData = ( setTableItems(docs); setStatus(INDEX_STATUS.LOADED); } catch (e) { - setErrorMessage(getErrorMessage(e)); + setErrorMessage(extractErrorMessage(e)); setStatus(INDEX_STATUS.ERROR); } }; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.test.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.test.tsx index ac1c710e1d106..f833cf4708cec 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.test.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.test.tsx @@ -11,7 +11,6 @@ import { MlContext } from '../../../../../contexts/ml'; import { kibanaContextValueMock } from '../../../../../contexts/ml/__mocks__/kibana_context_value'; import { useCreateAnalyticsForm } from './use_create_analytics_form'; -import { getErrorMessage } from '../../../../../../../common/util/errors'; const getMountedHook = () => mountHook( @@ -21,28 +20,6 @@ const getMountedHook = () => ) ); -describe('getErrorMessage()', () => { - test('verify error message response formats', () => { - const customError1 = { - body: { statusCode: 403, error: 'Forbidden', message: 'the-error-message' }, - }; - const errorMessage1 = getErrorMessage(customError1); - expect(errorMessage1).toBe('Forbidden: the-error-message'); - - const customError2 = new Error('the-error-message'); - const errorMessage2 = getErrorMessage(customError2); - expect(errorMessage2).toBe('the-error-message'); - - const customError3 = { customErrorMessage: 'the-error-message' }; - const errorMessage3 = getErrorMessage(customError3); - expect(errorMessage3).toBe('{"customErrorMessage":"the-error-message"}'); - - const customError4 = { message: 'the-error-message' }; - const errorMessage4 = getErrorMessage(customError4); - expect(errorMessage4).toBe('the-error-message'); - }); -}); - describe('useCreateAnalyticsForm()', () => { test('initialization', () => { const { getLastHookValue } = getMountedHook(); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts index 9612b9213d120..161dde51df43e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts @@ -8,7 +8,7 @@ import { useReducer } from 'react'; import { i18n } from '@kbn/i18n'; -import { getErrorMessage } from '../../../../../../../common/util/errors'; +import { extractErrorMessage } from '../../../../../../../common/util/errors'; import { DeepReadonly } from '../../../../../../../common/types/common'; import { ml } from '../../../../../services/ml_api_service'; import { useMlContext } from '../../../../../contexts/ml'; @@ -115,7 +115,7 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { refresh(); } catch (e) { addRequestMessage({ - error: getErrorMessage(e), + error: extractErrorMessage(e), message: i18n.translate( 'xpack.ml.dataframe.analytics.create.errorCreatingDataFrameAnalyticsJob', { @@ -178,7 +178,7 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { }); } catch (e) { addRequestMessage({ - error: getErrorMessage(e), + error: extractErrorMessage(e), message: i18n.translate( 'xpack.ml.dataframe.analytics.create.createIndexPatternErrorMessage', { @@ -199,7 +199,7 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { ); } catch (e) { addRequestMessage({ - error: getErrorMessage(e), + error: extractErrorMessage(e), message: i18n.translate( 'xpack.ml.dataframe.analytics.create.errorGettingDataFrameAnalyticsList', { @@ -225,7 +225,7 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { }); } catch (e) { addRequestMessage({ - error: getErrorMessage(e), + error: extractErrorMessage(e), message: i18n.translate( 'xpack.ml.dataframe.analytics.create.errorGettingIndexPatternTitles', { @@ -260,7 +260,7 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { refresh(); } catch (e) { addRequestMessage({ - error: getErrorMessage(e), + error: extractErrorMessage(e), message: i18n.translate( 'xpack.ml.dataframe.analytics.create.errorStartingDataFrameAnalyticsJob', { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts index 9de859742438e..a21be83732613 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts @@ -85,12 +85,11 @@ export const deleteAnalyticsAndDestIndex = async ( ); } if (status.destIndexDeleted?.error) { - const error = extractErrorMessage(status.destIndexDeleted.error); - toastNotificationService.displayDangerToast( + toastNotificationService.displayErrorToast( + status.destIndexDeleted.error, i18n.translate('xpack.ml.dataframe.analyticsList.deleteAnalyticsWithIndexErrorMessage', { - defaultMessage: - 'An error occurred deleting destination index {destinationIndex}: {error}', - values: { destinationIndex, error }, + defaultMessage: 'An error occurred deleting destination index {destinationIndex}', + values: { destinationIndex }, }) ); } diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.test.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.test.js index d705e47a5e906..58adf3d892f66 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.test.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.test.js @@ -8,8 +8,6 @@ import mockAnomalyRecord from './__mocks__/mock_anomaly_record.json'; import mockDetectorsByJob from './__mocks__/mock_detectors_by_job.json'; import mockJobConfig from './__mocks__/mock_job_config.json'; -jest.mock('../../util/ml_error', () => class MLRequestFailure {}); - jest.mock('../../services/job_service', () => ({ mlJobService: { getJob() { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js index 9d0082ffcb568..bd781d32a6b06 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js @@ -7,6 +7,8 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { cloneDeep, isEqual, pick } from 'lodash'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; import { EuiButton, EuiButtonEmpty, @@ -28,8 +30,6 @@ import { loadFullJob } from '../utils'; import { validateModelMemoryLimit, validateGroupNames, isValidCustomUrls } from '../validate_job'; import { toastNotificationServiceProvider } from '../../../../services/toast_notification_service'; import { withKibana } from '../../../../../../../../../src/plugins/kibana_react/public'; -import { i18n } from '@kbn/i18n'; -import { FormattedMessage } from '@kbn/i18n/react'; import { collapseLiteralStrings } from '../../../../../../shared_imports'; import { DATAFEED_STATE } from '../../../../../../common/constants/states'; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js index 5030c48a4e367..adcc576c5e356 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js @@ -6,9 +6,9 @@ import { difference } from 'lodash'; import { getNewJobLimits } from '../../../../services/ml_server_info'; -import { mlJobService } from '../../../../services/job_service'; import { processCreatedBy } from '../../../../../../common/util/job_utils'; import { getSavedObjectsClient } from '../../../../util/dependency_cache'; +import { ml } from '../../../../services/ml_api_service'; export function saveJob(job, newJobData, finish) { return new Promise((resolve, reject) => { @@ -41,14 +41,9 @@ export function saveJob(job, newJobData, finish) { // if anything has changed, post the changes if (Object.keys(jobData).length) { - mlJobService - .updateJob(job.job_id, jobData) - .then((resp) => { - if (resp.success) { - saveDatafeedWrapper(); - } else { - reject(resp); - } + ml.updateJob({ jobId: job.job_id, job: jobData }) + .then(() => { + saveDatafeedWrapper(); }) .catch((error) => { reject(error); @@ -59,17 +54,17 @@ export function saveJob(job, newJobData, finish) { }); } -function saveDatafeed(datafeedData, job) { +function saveDatafeed(datafeedConfig, job) { return new Promise((resolve, reject) => { - if (Object.keys(datafeedData).length) { + if (Object.keys(datafeedConfig).length) { const datafeedId = job.datafeed_config.datafeed_id; - mlJobService.updateDatafeed(datafeedId, datafeedData).then((resp) => { - if (resp.success) { + ml.updateDatafeed({ datafeedId, datafeedConfig }) + .then(() => { resolve(); - } else { - reject(resp); - } - }); + }) + .catch((error) => { + reject(error); + }); } else { resolve(); } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js index f73dde69a3d4c..a379f49a83159 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js @@ -6,6 +6,8 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; import { EuiButton, @@ -25,9 +27,7 @@ import { ml } from '../../../../../services/ml_api_service'; import { checkPermission } from '../../../../../capabilities/check_capabilities'; import { GroupList } from './group_list'; import { NewGroupInput } from './new_group_input'; -import { mlMessageBarService } from '../../../../../components/messagebar'; -import { i18n } from '@kbn/i18n'; -import { FormattedMessage } from '@kbn/i18n/react'; +import { getToastNotificationService } from '../../../../../services/toast_notification_service'; function createSelectedGroups(jobs, groups) { const jobIds = jobs.map((j) => j.id); @@ -160,7 +160,7 @@ export class GroupSelector extends Component { // check success of each job update if (resp.hasOwnProperty(jobId)) { if (resp[jobId].success === false) { - mlMessageBarService.notify.error(resp[jobId].error); + getToastNotificationService().displayErrorToast(resp[jobId].error); success = false; } } @@ -175,7 +175,7 @@ export class GroupSelector extends Component { } }) .catch((error) => { - mlMessageBarService.notify.error(error); + getToastNotificationService().displayErrorToast(error); console.error(error); }); }; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js index 913727bda67df..21824aac18cdd 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js @@ -5,17 +5,19 @@ */ import { each } from 'lodash'; -import { mlMessageBarService } from '../../../components/messagebar'; +import { i18n } from '@kbn/i18n'; import rison from 'rison-node'; import { mlJobService } from '../../../services/job_service'; -import { toastNotificationServiceProvider } from '../../../services/toast_notification_service'; -import { ml } from '../../../services/ml_api_service'; +import { + getToastNotificationService, + toastNotificationServiceProvider, +} from '../../../services/toast_notification_service'; import { getToastNotifications } from '../../../util/dependency_cache'; +import { ml } from '../../../services/ml_api_service'; import { stringMatch } from '../../../util/string_utils'; import { JOB_STATE, DATAFEED_STATE } from '../../../../../common/constants/states'; import { parseInterval } from '../../../../../common/util/parse_interval'; -import { i18n } from '@kbn/i18n'; import { mlCalendarService } from '../../../services/calendar_service'; export function loadFullJob(jobId) { @@ -60,7 +62,6 @@ export function forceStartDatafeeds(jobs, start, end, finish = () => {}) { finish(); }) .catch((error) => { - mlMessageBarService.notify.error(error); const toastNotifications = getToastNotifications(); toastNotifications.addDanger( i18n.translate('xpack.ml.jobsList.startJobErrorMessage', { @@ -81,7 +82,6 @@ export function stopDatafeeds(jobs, finish = () => {}) { finish(); }) .catch((error) => { - mlMessageBarService.notify.error(error); const toastNotifications = getToastNotifications(); toastNotifications.addDanger( i18n.translate('xpack.ml.jobsList.stopJobErrorMessage', { @@ -219,9 +219,8 @@ export async function cloneJob(jobId) { window.location.href = '#/jobs/new_job'; } catch (error) { - mlMessageBarService.notify.error(error); - const toastNotifications = getToastNotifications(); - toastNotifications.addDanger( + getToastNotificationService().displayErrorToast( + error, i18n.translate('xpack.ml.jobsList.cloneJobErrorMessage', { defaultMessage: 'Could not clone {jobId}. Job could not be found', values: { jobId }, @@ -239,13 +238,11 @@ export function closeJobs(jobs, finish = () => {}) { finish(); }) .catch((error) => { - mlMessageBarService.notify.error(error); - const toastNotifications = getToastNotifications(); - toastNotifications.addDanger( + getToastNotificationService().displayErrorToast( + error, i18n.translate('xpack.ml.jobsList.closeJobErrorMessage', { defaultMessage: 'Jobs failed to close', - }), - error + }) ); finish(); }); @@ -260,13 +257,11 @@ export function deleteJobs(jobs, finish = () => {}) { finish(); }) .catch((error) => { - mlMessageBarService.notify.error(error); - const toastNotifications = getToastNotifications(); - toastNotifications.addDanger( + getToastNotificationService().displayErrorToast( + error, i18n.translate('xpack.ml.jobsList.deleteJobErrorMessage', { defaultMessage: 'Jobs failed to delete', - }), - error + }) ); finish(); }); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts index 0011c88d2b524..6671aaa83abe0 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts @@ -23,7 +23,7 @@ import { useEffect, useMemo } from 'react'; import { DEFAULT_MODEL_MEMORY_LIMIT } from '../../../../../../../common/constants/new_job'; import { ml } from '../../../../../services/ml_api_service'; import { JobValidator, VALIDATION_DELAY_MS } from '../../job_validator/job_validator'; -import { ErrorResponse } from '../../../../../../../common/types/errors'; +import { MLHttpFetchError, MLResponseError } from '../../../../../../../common/util/errors'; import { useMlKibana } from '../../../../../contexts/kibana'; import { JobCreator } from '../job_creator'; @@ -36,10 +36,10 @@ export const modelMemoryEstimatorProvider = ( jobValidator: JobValidator ) => { const modelMemoryCheck$ = new Subject(); - const error$ = new Subject(); + const error$ = new Subject>(); return { - get error$(): Observable { + get error$(): Observable> { return error$.asObservable(); }, get updates$(): Observable { @@ -64,7 +64,7 @@ export const modelMemoryEstimatorProvider = ( catchError((error) => { // eslint-disable-next-line no-console console.error('Model memory limit could not be calculated', error.body); - error$.next(error.body); + error$.next(error); // fallback to the default in case estimation failed return of(DEFAULT_MODEL_MEMORY_LIMIT); }) @@ -120,7 +120,8 @@ export const useModelMemoryEstimator = ( title: i18n.translate('xpack.ml.newJob.wizard.estimateModelMemoryError', { defaultMessage: 'Model memory limit could not be calculated', }), - text: error.message, + text: + error.body.attributes?.body.error.caused_by?.reason || error.body.message || undefined, }); }) ); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts index 0ec3b609b604f..a87ba4c29baa9 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts @@ -15,7 +15,7 @@ import { } from '../../../../../common/job_creator'; import { ml, BucketSpanEstimatorData } from '../../../../../../../services/ml_api_service'; import { useMlContext } from '../../../../../../../contexts/ml'; -import { mlMessageBarService } from '../../../../../../../components/messagebar'; +import { getToastNotificationService } from '../../../../../../../services/toast_notification_service'; export enum ESTIMATE_STATUS { NOT_RUNNING, @@ -68,7 +68,7 @@ export function useEstimateBucketSpan() { const { name, error, message } = await ml.estimateBucketSpan(data); setStatus(ESTIMATE_STATUS.NOT_RUNNING); if (error === true) { - mlMessageBarService.notify.error(message); + getToastNotificationService().displayErrorToast(message); } else { jobCreator.bucketSpan = name; jobCreatorUpdate(); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection.tsx index cbbddb5bbc5b8..da2e5cc0e63d9 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection.tsx @@ -6,7 +6,7 @@ import React, { FC, useContext, useEffect, useState } from 'react'; import { EuiHorizontalRule } from '@elastic/eui'; -import { mlMessageBarService } from '../../../../../../../components/messagebar'; +import { getToastNotificationService } from '../../../../../../../services/toast_notification_service'; import { JobCreatorContext } from '../../../job_creator_context'; import { CategorizationJobCreator } from '../../../../../common/job_creator'; @@ -94,7 +94,7 @@ export const CategorizationDetectors: FC = ({ setIsValid }) => { setFieldExamples(null); setValidationChecks([]); setOverallValidStatus(CATEGORY_EXAMPLES_VALIDATION_STATUS.INVALID); - mlMessageBarService.notify.error(error); + getToastNotificationService().displayErrorToast(error); } } else { setFieldExamples(null); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx index 684cb5b4e0dda..762d18a5367f1 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx @@ -15,7 +15,7 @@ import { AggFieldPair } from '../../../../../../../../../common/types/fields'; import { getChartSettings, defaultChartSettings } from '../../../charts/common/settings'; import { MetricSelector } from './metric_selector'; import { ChartGrid } from './chart_grid'; -import { mlMessageBarService } from '../../../../../../../components/messagebar'; +import { getToastNotificationService } from '../../../../../../../services/toast_notification_service'; interface Props { setIsValid: (na: boolean) => void; @@ -109,7 +109,7 @@ export const MultiMetricDetectors: FC = ({ setIsValid }) => { .loadFieldExampleValues(splitField) .then(setFieldValues) .catch((error) => { - mlMessageBarService.notify.error(error); + getToastNotificationService().displayErrorToast(error); }); } else { setFieldValues([]); @@ -138,7 +138,7 @@ export const MultiMetricDetectors: FC = ({ setIsValid }) => { ); setLineChartsData(resp); } catch (error) { - mlMessageBarService.notify.error(error); + getToastNotificationService().displayErrorToast(error); setLineChartsData([]); } setLoadingData(false); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx index f39a316440e74..cc0fbf2fc0a04 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx @@ -12,7 +12,7 @@ import { Results, ModelItem, Anomaly } from '../../../../../common/results_loade import { LineChartData } from '../../../../../common/chart_loader'; import { getChartSettings, defaultChartSettings } from '../../../charts/common/settings'; import { ChartGrid } from './chart_grid'; -import { mlMessageBarService } from '../../../../../../../components/messagebar'; +import { getToastNotificationService } from '../../../../../../../services/toast_notification_service'; export const MultiMetricDetectorsSummary: FC = () => { const { jobCreator: jc, chartLoader, resultsLoader, chartInterval } = useContext( @@ -43,7 +43,7 @@ export const MultiMetricDetectorsSummary: FC = () => { const tempFieldValues = await chartLoader.loadFieldExampleValues(jobCreator.splitField); setFieldValues(tempFieldValues); } catch (error) { - mlMessageBarService.notify.error(error); + getToastNotificationService().displayErrorToast(error); } } })(); @@ -75,7 +75,7 @@ export const MultiMetricDetectorsSummary: FC = () => { ); setLineChartsData(resp); } catch (error) { - mlMessageBarService.notify.error(error); + getToastNotificationService().displayErrorToast(error); setLineChartsData({}); } setLoadingData(false); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx index e5f5ba48900d9..46f91550f6e32 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx @@ -17,7 +17,7 @@ import { getChartSettings, defaultChartSettings } from '../../../charts/common/s import { MetricSelector } from './metric_selector'; import { SplitFieldSelector } from '../split_field'; import { ChartGrid } from './chart_grid'; -import { mlMessageBarService } from '../../../../../../../components/messagebar'; +import { getToastNotificationService } from '../../../../../../../services/toast_notification_service'; interface Props { setIsValid: (na: boolean) => void; @@ -159,7 +159,7 @@ export const PopulationDetectors: FC = ({ setIsValid }) => { setLineChartsData(resp); } catch (error) { - mlMessageBarService.notify.error(error); + getToastNotificationService().displayErrorToast(error); setLineChartsData([]); } setLoadingData(false); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx index 06f7092e8ac06..c32cc6ecc445a 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx @@ -15,7 +15,7 @@ import { LineChartData } from '../../../../../common/chart_loader'; import { Field, AggFieldPair } from '../../../../../../../../../common/types/fields'; import { getChartSettings, defaultChartSettings } from '../../../charts/common/settings'; import { ChartGrid } from './chart_grid'; -import { mlMessageBarService } from '../../../../../../../components/messagebar'; +import { getToastNotificationService } from '../../../../../../../services/toast_notification_service'; type DetectorFieldValues = Record; @@ -81,7 +81,7 @@ export const PopulationDetectorsSummary: FC = () => { setLineChartsData(resp); } catch (error) { - mlMessageBarService.notify.error(error); + getToastNotificationService().displayErrorToast(error); setLineChartsData({}); } setLoadingData(false); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx index f04b63f47789e..5844e59225ab5 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx @@ -13,7 +13,7 @@ import { newJobCapsService } from '../../../../../../../services/new_job_capabil import { AggFieldPair } from '../../../../../../../../../common/types/fields'; import { AnomalyChart, CHART_TYPE } from '../../../charts/anomaly_chart'; import { getChartSettings } from '../../../charts/common/settings'; -import { mlMessageBarService } from '../../../../../../../components/messagebar'; +import { getToastNotificationService } from '../../../../../../../services/toast_notification_service'; interface Props { setIsValid: (na: boolean) => void; @@ -93,7 +93,7 @@ export const SingleMetricDetectors: FC = ({ setIsValid }) => { setLineChartData(resp); } } catch (error) { - mlMessageBarService.notify.error(error); + getToastNotificationService().displayErrorToast(error); setLineChartData({}); } setLoadingData(false); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx index 85fb5890307ba..ae019ee1bbf84 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx @@ -11,7 +11,7 @@ import { Results, ModelItem, Anomaly } from '../../../../../common/results_loade import { LineChartData } from '../../../../../common/chart_loader'; import { AnomalyChart, CHART_TYPE } from '../../../charts/anomaly_chart'; import { getChartSettings } from '../../../charts/common/settings'; -import { mlMessageBarService } from '../../../../../../../components/messagebar'; +import { getToastNotificationService } from '../../../../../../../services/toast_notification_service'; const DTR_IDX = 0; @@ -63,7 +63,7 @@ export const SingleMetricDetectorsSummary: FC = () => { setLineChartData(resp); } } catch (error) { - mlMessageBarService.notify.error(error); + getToastNotificationService().displayErrorToast(error); setLineChartData({}); } setLoadingData(false); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/summary_step/components/post_save_options/post_save_options.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/summary_step/components/post_save_options/post_save_options.tsx index 2e7cc9c413a25..82a023cd1779b 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/summary_step/components/post_save_options/post_save_options.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/summary_step/components/post_save_options/post_save_options.tsx @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { JobRunner } from '../../../../../common/job_runner'; import { useMlKibana } from '../../../../../../../contexts/kibana'; -import { getErrorMessage } from '../../../../../../../../../common/util/errors'; +import { extractErrorMessage } from '../../../../../../../../../common/util/errors'; // @ts-ignore import { CreateWatchFlyout } from '../../../../../../jobs_list/components/create_watch_flyout/index'; @@ -70,7 +70,7 @@ export const PostSaveOptions: FC = ({ jobRunner }) => { defaultMessage: `Error starting job`, } ), - text: getErrorMessage(error), + text: extractErrorMessage(error), }); } } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/summary_step/summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/summary_step/summary.tsx index 24d7fb9fc2a40..3000ce8449138 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/summary_step/summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/summary_step/summary.tsx @@ -22,13 +22,13 @@ import { JobCreatorContext } from '../job_creator_context'; import { JobRunner } from '../../../common/job_runner'; import { mlJobService } from '../../../../../services/job_service'; import { JsonEditorFlyout, EDITOR_MODE } from '../common/json_editor_flyout'; -import { getErrorMessage } from '../../../../../../../common/util/errors'; import { isSingleMetricJobCreator, isAdvancedJobCreator } from '../../../common/job_creator'; import { JobDetails } from './components/job_details'; import { DatafeedDetails } from './components/datafeed_details'; import { DetectorChart } from './components/detector_chart'; import { JobProgress } from './components/job_progress'; import { PostSaveOptions } from './components/post_save_options'; +import { toastNotificationServiceProvider } from '../../../../../services/toast_notification_service'; import { convertToAdvancedJob, resetJob, @@ -72,15 +72,7 @@ export const SummaryStep: FC = ({ setCurrentStep, isCurrentStep }) => const jr = await jobCreator.createAndStartJob(); setJobRunner(jr); } catch (error) { - // catch and display all job creation errors - const { toasts } = notifications; - toasts.addDanger({ - title: i18n.translate('xpack.ml.newJob.wizard.summaryStep.createJobError', { - defaultMessage: `Job creation error`, - }), - text: getErrorMessage(error), - }); - setCreatingJob(false); + handleJobCreationError(error); } } @@ -91,18 +83,21 @@ export const SummaryStep: FC = ({ setCurrentStep, isCurrentStep }) => await jobCreator.createDatafeed(); advancedStartDatafeed(jobCreator, navigateToPath); } catch (error) { - // catch and display all job creation errors - const { toasts } = notifications; - toasts.addDanger({ - title: i18n.translate('xpack.ml.newJob.wizard.summaryStep.createJobError', { - defaultMessage: `Job creation error`, - }), - text: getErrorMessage(error), - }); - setCreatingJob(false); + handleJobCreationError(error); } } + function handleJobCreationError(error: any) { + const { displayErrorToast } = toastNotificationServiceProvider(notifications.toasts); + displayErrorToast( + error, + i18n.translate('xpack.ml.newJob.wizard.summaryStep.createJobError', { + defaultMessage: `Job creation error`, + }) + ); + setCreatingJob(false); + } + function viewResults() { const url = mlJobService.createResultsUrl( [jobCreator.jobId], diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/validation_step/validation.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/validation_step/validation.tsx index 19b89ffec02ac..3bde32f40eeb5 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/validation_step/validation.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/validation_step/validation.tsx @@ -8,7 +8,7 @@ import React, { Fragment, FC, useContext, useState, useEffect } from 'react'; import { WizardNav } from '../wizard_nav'; import { WIZARD_STEPS, StepProps } from '../step_types'; import { JobCreatorContext } from '../job_creator_context'; -import { mlJobService } from '../../../../../services/job_service'; +import { ml } from '../../../../../services/ml_api_service'; import { ValidateJob } from '../../../../../components/validate_job'; import { JOB_TYPE } from '../../../../../../../common/constants/new_job'; @@ -66,7 +66,7 @@ export const ValidationStep: FC = ({ setCurrentStep, isCurrentStep }) { jobs = []; datafeedIds = {}; - ml.getJobs() .then((resp) => { jobs = resp.jobs; @@ -162,7 +159,6 @@ class JobService { } processBasicJobInfo(this, jobs); this.jobs = jobs; - createJobStats(this.jobs, this.jobStats); resolve({ jobs: this.jobs }); }); }) @@ -176,12 +172,7 @@ class JobService { function error(err) { console.log('jobService error getting list of jobs:', err); - msgs.notify.error( - i18n.translate('xpack.ml.jobService.jobsListCouldNotBeRetrievedErrorMessage', { - defaultMessage: 'Jobs list could not be retrieved', - }) - ); - msgs.notify.error('', err); + getToastNotificationService().displayErrorToast(err); reject({ jobs, err }); } }); @@ -248,7 +239,6 @@ class JobService { } } this.jobs = jobs; - createJobStats(this.jobs, this.jobStats); resolve({ jobs: this.jobs }); }); }) @@ -263,12 +253,7 @@ class JobService { function error(err) { console.log('JobService error getting list of jobs:', err); - msgs.notify.error( - i18n.translate('xpack.ml.jobService.jobsListCouldNotBeRetrievedErrorMessage', { - defaultMessage: 'Jobs list could not be retrieved', - }) - ); - msgs.notify.error('', err); + getToastNotificationService().displayErrorToast(err); reject({ jobs, err }); } }); @@ -280,9 +265,6 @@ class JobService { ml.getDatafeeds(sId) .then((resp) => { - // console.log('loadDatafeeds query response:', resp); - - // make deep copy of datafeeds const datafeeds = resp.datafeeds; // load datafeeds stats @@ -309,12 +291,7 @@ class JobService { function error(err) { console.log('loadDatafeeds error getting list of datafeeds:', err); - msgs.notify.error( - i18n.translate('xpack.ml.jobService.datafeedsListCouldNotBeRetrievedErrorMessage', { - defaultMessage: 'datafeeds list could not be retrieved', - }) - ); - msgs.notify.error('', err); + getToastNotificationService().displayErrorToast(err); reject({ jobs, err }); } }); @@ -415,62 +392,6 @@ class JobService { return tempJob; } - updateJob(jobId, job) { - // return the promise chain - return ml - .updateJob({ jobId, job }) - .then(() => { - return { success: true }; - }) - .catch((err) => { - // TODO - all the functions in here should just return the error and not - // display the toast, as currently both the component and this service display - // errors, so we end up with duplicate toasts. - const toastNotifications = getToastNotifications(); - const toastNotificationService = toastNotificationServiceProvider(toastNotifications); - toastNotificationService.displayErrorToast( - err, - i18n.translate('xpack.ml.jobService.updateJobErrorTitle', { - defaultMessage: 'Could not update job: {jobId}', - values: { jobId }, - }) - ); - - console.error('update job', err); - return { success: false, message: err }; - }); - } - - validateJob(obj) { - // return the promise chain - return ml - .validateJob(obj) - .then((messages) => { - return { success: true, messages }; - }) - .catch((err) => { - const toastNotifications = getToastNotifications(); - const toastNotificationService = toastNotificationServiceProvider(toastNotifications); - toastNotificationService.displayErrorToast( - err, - i18n.translate('xpack.ml.jobService.validateJobErrorTitle', { - defaultMessage: 'Job Validation Error', - }) - ); - - console.log('validate job', err); - return { - success: false, - messages: [ - { - status: 'error', - text: err.message, - }, - ], - }; - }); - } - // find a job based on the id getJob(jobId) { const job = find(jobs, (j) => { @@ -638,25 +559,6 @@ class JobService { }); } - updateDatafeed(datafeedId, datafeedConfig) { - return ml - .updateDatafeed({ datafeedId, datafeedConfig }) - .then((resp) => { - console.log('update datafeed', resp); - return { success: true }; - }) - .catch((err) => { - msgs.notify.error( - i18n.translate('xpack.ml.jobService.couldNotUpdateDatafeedErrorMessage', { - defaultMessage: 'Could not update datafeed: {datafeedId}', - values: { datafeedId }, - }) - ); - console.log('update datafeed', err); - return { success: false, message: err.message }; - }); - } - // start the datafeed for a given job // refresh the job state on start success startDatafeed(datafeedId, jobId, start, end) { @@ -677,49 +579,6 @@ class JobService { }) .catch((err) => { console.log('jobService error starting datafeed:', err); - msgs.notify.error( - i18n.translate('xpack.ml.jobService.couldNotStartDatafeedErrorMessage', { - defaultMessage: 'Could not start datafeed for {jobId}', - values: { jobId }, - }), - err - ); - reject(err); - }); - }); - } - - // stop the datafeed for a given job - // refresh the job state on stop success - stopDatafeed(datafeedId, jobId) { - return new Promise((resolve, reject) => { - ml.stopDatafeed({ - datafeedId, - }) - .then((resp) => { - resolve(resp); - }) - .catch((err) => { - console.log('jobService error stopping datafeed:', err); - const couldNotStopDatafeedErrorMessage = i18n.translate( - 'xpack.ml.jobService.couldNotStopDatafeedErrorMessage', - { - defaultMessage: 'Could not stop datafeed for {jobId}', - values: { jobId }, - } - ); - - if (err.statusCode === 500) { - msgs.notify.error(couldNotStopDatafeedErrorMessage); - msgs.notify.error( - i18n.translate('xpack.ml.jobService.requestMayHaveTimedOutErrorMessage', { - defaultMessage: - 'Request may have timed out and may still be running in the background.', - }) - ); - } else { - msgs.notify.error(couldNotStopDatafeedErrorMessage, err); - } reject(err); }); }); @@ -887,51 +746,6 @@ function processBasicJobInfo(localJobService, jobsList) { return processedJobsList; } -// Loop through the jobs list and create basic stats -// stats are displayed along the top of the Jobs Management page -function createJobStats(jobsList, jobStats) { - jobStats.activeNodes.value = 0; - jobStats.total.value = 0; - jobStats.open.value = 0; - jobStats.closed.value = 0; - jobStats.failed.value = 0; - jobStats.activeDatafeeds.value = 0; - - // object to keep track of nodes being used by jobs - const mlNodes = {}; - let failedJobs = 0; - - each(jobsList, (job) => { - if (job.state === 'opened') { - jobStats.open.value++; - } else if (job.state === 'closed') { - jobStats.closed.value++; - } else if (job.state === 'failed') { - failedJobs++; - } - - if (job.datafeed_config && job.datafeed_config.state === 'started') { - jobStats.activeDatafeeds.value++; - } - - if (job.node && job.node.name) { - mlNodes[job.node.name] = {}; - } - }); - - jobStats.total.value = jobsList.length; - - // // Only show failed jobs if it is non-zero - if (failedJobs) { - jobStats.failed.value = failedJobs; - jobStats.failed.show = true; - } else { - jobStats.failed.show = false; - } - - jobStats.activeNodes.value = Object.keys(mlNodes).length; -} - function createResultsUrlForJobs(jobsList, resultsPage, userTimeRange) { let from = undefined; let to = undefined; diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts index 9d7ce4f3df59b..0deda455df771 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts @@ -62,7 +62,7 @@ export interface BucketSpanEstimatorResponse { name: string; ms: number; error?: boolean; - message?: { msg: string } | string; + message?: string; } export interface GetTimeFieldRangeResponse { diff --git a/x-pack/plugins/ml/public/application/services/toast_notification_service.ts b/x-pack/plugins/ml/public/application/services/toast_notification_service.ts deleted file mode 100644 index 94381ae3f1e51..0000000000000 --- a/x-pack/plugins/ml/public/application/services/toast_notification_service.ts +++ /dev/null @@ -1,88 +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 { ToastInput, ToastOptions, ToastsStart } from 'kibana/public'; -import { ResponseError } from 'kibana/server'; -import { useMemo } from 'react'; -import { useNotifications } from '../contexts/kibana'; -import { - BoomResponse, - extractErrorProperties, - MLCustomHttpResponseOptions, - MLErrorObject, - MLResponseError, -} from '../../../common/util/errors'; - -export type ToastNotificationService = ReturnType; - -export function toastNotificationServiceProvider(toastNotifications: ToastsStart) { - return { - displayDangerToast(toastOrTitle: ToastInput, options?: ToastOptions) { - toastNotifications.addDanger(toastOrTitle, options); - }, - - displaySuccessToast(toastOrTitle: ToastInput, options?: ToastOptions) { - toastNotifications.addSuccess(toastOrTitle, options); - }, - - displayErrorToast(error: any, toastTitle: string) { - const errorObj = this.parseErrorMessage(error); - if (errorObj.fullErrorMessage !== undefined) { - // Provide access to the full error message via the 'See full error' button. - toastNotifications.addError(new Error(errorObj.fullErrorMessage), { - title: toastTitle, - toastMessage: errorObj.message, - }); - } else { - toastNotifications.addDanger( - { - title: toastTitle, - text: errorObj.message, - }, - { toastLifeTimeMs: 30000 } - ); - } - }, - - parseErrorMessage( - error: - | MLCustomHttpResponseOptions - | undefined - | string - | MLResponseError - ): MLErrorObject { - if ( - typeof error === 'object' && - 'response' in error && - typeof error.response === 'string' && - error.statusCode !== undefined - ) { - // MLResponseError which has been received back as part of a 'successful' response - // where the error was passed in a separate property in the response. - const wrapMlResponseError = { - body: error, - statusCode: error.statusCode, - }; - return extractErrorProperties(wrapMlResponseError); - } - - return extractErrorProperties( - error as - | MLCustomHttpResponseOptions - | undefined - | string - ); - }, - }; -} - -/** - * Hook to use {@link ToastNotificationService} in React components. - */ -export function useToastNotificationService(): ToastNotificationService { - const { toasts } = useNotifications(); - return useMemo(() => toastNotificationServiceProvider(toasts), []); -} diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/index.ts b/x-pack/plugins/ml/public/application/services/toast_notification_service/index.ts similarity index 58% rename from x-pack/plugins/security_solution/public/common/lib/connectors/index.ts rename to x-pack/plugins/ml/public/application/services/toast_notification_service/index.ts index 33afa82c84f34..1259f3b47d8e0 100644 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/index.ts +++ b/x-pack/plugins/ml/public/application/services/toast_notification_service/index.ts @@ -4,4 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -export { getActionType as resilientActionType } from './resilient'; +export { + ToastNotificationService, + toastNotificationServiceProvider, + useToastNotificationService, + getToastNotificationService, +} from './toast_notification_service'; diff --git a/x-pack/plugins/ml/public/application/services/toast_notification_service/toast_notification_service.ts b/x-pack/plugins/ml/public/application/services/toast_notification_service/toast_notification_service.ts new file mode 100644 index 0000000000000..61e0480313ebe --- /dev/null +++ b/x-pack/plugins/ml/public/application/services/toast_notification_service/toast_notification_service.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 { ToastInput, ToastOptions, ToastsStart } from 'kibana/public'; +import { useMemo } from 'react'; +import { getToastNotifications } from '../../util/dependency_cache'; +import { useNotifications } from '../../contexts/kibana'; +import { + ErrorType, + extractErrorProperties, + MLRequestFailure, +} from '../../../../common/util/errors'; + +export type ToastNotificationService = ReturnType; + +export function toastNotificationServiceProvider(toastNotifications: ToastsStart) { + function displayDangerToast(toastOrTitle: ToastInput, options?: ToastOptions) { + toastNotifications.addDanger(toastOrTitle, options); + } + + function displayWarningToast(toastOrTitle: ToastInput, options?: ToastOptions) { + toastNotifications.addWarning(toastOrTitle, options); + } + + function displaySuccessToast(toastOrTitle: ToastInput, options?: ToastOptions) { + toastNotifications.addSuccess(toastOrTitle, options); + } + + function displayErrorToast(error: ErrorType, title?: string) { + const errorObj = extractErrorProperties(error); + toastNotifications.addError(new MLRequestFailure(errorObj, error), { + title: + title ?? + i18n.translate('xpack.ml.toastNotificationService.errorTitle', { + defaultMessage: 'An error has occurred', + }), + }); + } + + return { displayDangerToast, displayWarningToast, displaySuccessToast, displayErrorToast }; +} + +export function getToastNotificationService() { + const toastNotifications = getToastNotifications(); + return toastNotificationServiceProvider(toastNotifications); +} + +/** + * Hook to use {@link ToastNotificationService} in React components. + */ +export function useToastNotificationService(): ToastNotificationService { + const { toasts } = useNotifications(); + return useMemo(() => toastNotificationServiceProvider(toasts), []); +} diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/delete_calendars.js b/x-pack/plugins/ml/public/application/settings/calendars/list/delete_calendars.js index 50777485903d2..e0c7a4db6e898 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/delete_calendars.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/delete_calendars.js @@ -7,7 +7,7 @@ import { getToastNotifications } from '../../../util/dependency_cache'; import { ml } from '../../../services/ml_api_service'; import { i18n } from '@kbn/i18n'; -import { getErrorMessage } from '../../../../../common/util/errors'; +import { extractErrorMessage } from '../../../../../common/util/errors'; export async function deleteCalendars(calendarsToDelete, callback) { if (calendarsToDelete === undefined || calendarsToDelete.length === 0) { @@ -47,7 +47,7 @@ export async function deleteCalendars(calendarsToDelete, callback) { }, } ), - text: getErrorMessage(error), + text: extractErrorMessage(error), }); } } diff --git a/x-pack/plugins/ml/public/application/util/ml_error.ts b/x-pack/plugins/ml/public/application/util/ml_error.ts deleted file mode 100644 index 2a0280404c189..0000000000000 --- a/x-pack/plugins/ml/public/application/util/ml_error.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { KbnError } from '../../../../../../src/plugins/kibana_utils/public'; - -export class MLRequestFailure extends KbnError { - origError: any; - resp: any; - // takes an Error object and and optional response object - // if error is falsy (null) the response object will be used - // notify will show the full expandable stack trace of the response if a response object is used and no error is passed in. - constructor(error: any, resp: any) { - error = error || {}; - super(error.message || JSON.stringify(resp)); - - this.origError = error; - this.resp = typeof resp === 'string' ? JSON.parse(resp) : resp; - } -} diff --git a/x-pack/plugins/ml/server/models/job_service/datafeeds.ts b/x-pack/plugins/ml/server/models/job_service/datafeeds.ts index c0eb1b72825df..62ef9b3621610 100644 --- a/x-pack/plugins/ml/server/models/job_service/datafeeds.ts +++ b/x-pack/plugins/ml/server/models/job_service/datafeeds.ts @@ -118,6 +118,11 @@ export function datafeedsProvider({ asInternalUser }: IScopedClusterClient) { } catch (error) { if (isRequestTimeout(error)) { return fillResultsWithTimeouts(results, datafeedId, datafeedIds, DATAFEED_STATE.STOPPED); + } else { + results[datafeedId] = { + started: false, + error: error.body, + }; } } } diff --git a/x-pack/plugins/ml/server/routes/data_frame_analytics.ts b/x-pack/plugins/ml/server/routes/data_frame_analytics.ts index 7606420eacefc..4dad12af5e684 100644 --- a/x-pack/plugins/ml/server/routes/data_frame_analytics.ts +++ b/x-pack/plugins/ml/server/routes/data_frame_analytics.ts @@ -325,19 +325,20 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense }: RouteInitializat success: false, }; - // Check if analyticsId is valid and get destination index - if (deleteDestIndex || deleteDestIndexPattern) { - try { - const { body } = await client.asInternalUser.ml.getDataFrameAnalytics({ - id: analyticsId, - }); - if (Array.isArray(body.data_frame_analytics) && body.data_frame_analytics.length > 0) { - destinationIndex = body.data_frame_analytics[0].dest.index; - } - } catch (e) { - return response.customError(wrapError(e)); + try { + // Check if analyticsId is valid and get destination index + const { body } = await client.asInternalUser.ml.getDataFrameAnalytics({ + id: analyticsId, + }); + if (Array.isArray(body.data_frame_analytics) && body.data_frame_analytics.length > 0) { + destinationIndex = body.data_frame_analytics[0].dest.index; } + } catch (e) { + // exist early if the job doesn't exist + return response.customError(wrapError(e)); + } + if (deleteDestIndex || deleteDestIndexPattern) { // If user checks box to delete the destinationIndex associated with the job if (destinationIndex && deleteDestIndex) { // Verify if user has privilege to delete the destination index @@ -349,8 +350,8 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense }: RouteInitializat index: destinationIndex, }); destIndexDeleted.success = true; - } catch (deleteIndexError) { - destIndexDeleted.error = wrapError(deleteIndexError); + } catch ({ body }) { + destIndexDeleted.error = body; } } else { return response.forbidden(); @@ -366,7 +367,7 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense }: RouteInitializat } destIndexPatternDeleted.success = true; } catch (deleteDestIndexPatternError) { - destIndexPatternDeleted.error = wrapError(deleteDestIndexPatternError); + destIndexPatternDeleted.error = deleteDestIndexPatternError; } } } @@ -378,11 +379,8 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense }: RouteInitializat id: analyticsId, }); analyticsJobDeleted.success = true; - } catch (deleteDFAError) { - analyticsJobDeleted.error = wrapError(deleteDFAError); - if (analyticsJobDeleted.error.statusCode === 404) { - return response.notFound(); - } + } catch ({ body }) { + analyticsJobDeleted.error = body; } const results = { analyticsJobDeleted, diff --git a/x-pack/plugins/monitoring/public/views/access_denied/index.js b/x-pack/plugins/monitoring/public/views/access_denied/index.js index 2db34842b9324..9f1303f5be522 100644 --- a/x-pack/plugins/monitoring/public/views/access_denied/index.js +++ b/x-pack/plugins/monitoring/public/views/access_denied/index.js @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { kbnBaseUrl } from '../../../../../../src/plugins/kibana_legacy/common/kbn_base_url'; import { uiRoutes } from '../../angular/helpers/routes'; import template from './index.html'; @@ -35,7 +34,7 @@ uiRoutes.when('/access-denied', { const $interval = $injector.get('$interval'); // The template's "Back to Kibana" button click handler - this.goToKibanaURL = kbnBaseUrl; + this.goToKibanaURL = '/app/home'; // keep trying to load data in the background const accessPoller = $interval(() => tryPrivilege($http), 5 * 1000); // every 5 seconds diff --git a/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js b/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js index 16d42d896ca11..e91679eff2817 100644 --- a/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js +++ b/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js @@ -119,67 +119,75 @@ export async function getClustersFromRequest( // add alerts data if (isInCodePath(codePaths, [CODE_PATH_ALERTS])) { const alertsClient = req.getAlertsClient(); - if (alertsClient) { - for (const cluster of clusters) { - const verification = verifyMonitoringLicense(req.server); - if (!verification.enabled) { - // return metadata detailing that alerts is disabled because of the monitoring cluster license - cluster.alerts = { - alertsMeta: { - enabled: verification.enabled, - message: verification.message, // NOTE: this is only defined when the alert feature is disabled - }, - list: {}, - }; - continue; - } - - // check the license type of the production cluster for alerts feature support - const license = cluster.license || {}; - const prodLicenseInfo = checkLicenseForAlerts( - license.type, - license.status === 'active', - 'production' - ); - if (prodLicenseInfo.clusterAlerts.enabled) { - cluster.alerts = { - list: await fetchStatus( - alertsClient, - req.server.plugins.monitoring.info, - undefined, - cluster.cluster_uuid, - start, - end, - [] - ), - alertsMeta: { - enabled: true, - }, - }; - continue; - } + for (const cluster of clusters) { + const verification = verifyMonitoringLicense(req.server); + if (!verification.enabled) { + // return metadata detailing that alerts is disabled because of the monitoring cluster license + cluster.alerts = { + alertsMeta: { + enabled: verification.enabled, + message: verification.message, // NOTE: this is only defined when the alert feature is disabled + }, + list: {}, + }; + continue; + } + if (!alertsClient) { cluster.alerts = { list: {}, alertsMeta: { - enabled: true, - }, - clusterMeta: { enabled: false, - message: i18n.translate( - 'xpack.monitoring.clusterAlerts.unsupportedClusterAlertsDescription', - { - defaultMessage: - 'Cluster [{clusterName}] license type [{licenseType}] does not support Cluster Alerts', - values: { - clusterName: cluster.cluster_name, - licenseType: `${license.type}`, - }, - } - ), }, }; + continue; + } + + // check the license type of the production cluster for alerts feature support + const license = cluster.license || {}; + const prodLicenseInfo = checkLicenseForAlerts( + license.type, + license.status === 'active', + 'production' + ); + if (prodLicenseInfo.clusterAlerts.enabled) { + cluster.alerts = { + list: await fetchStatus( + alertsClient, + req.server.plugins.monitoring.info, + undefined, + cluster.cluster_uuid, + start, + end, + [] + ), + alertsMeta: { + enabled: true, + }, + }; + continue; } + + cluster.alerts = { + list: {}, + alertsMeta: { + enabled: false, + }, + clusterMeta: { + enabled: false, + message: i18n.translate( + 'xpack.monitoring.clusterAlerts.unsupportedClusterAlertsDescription', + { + defaultMessage: + 'Cluster [{clusterName}] license type [{licenseType}] does not support Cluster Alerts', + values: { + clusterName: cluster.cluster_name, + licenseType: `${license.type}`, + }, + } + ), + }, + }; } } } diff --git a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts index 5e38045b88c74..b393c4a9e1a04 100644 --- a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts +++ b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts @@ -31,7 +31,9 @@ beforeEach(() => { mockSpacesService = { getSpaceId: jest.fn(), - namespaceToSpaceId: jest.fn().mockImplementation((namespace: string) => `${namespace}-id`), + namespaceToSpaceId: jest + .fn() + .mockImplementation((namespace: string = 'default') => `${namespace}-id`), }; }); @@ -41,8 +43,6 @@ describe('#checkSavedObjectsPrivileges', () => { const namespace2 = 'qux'; describe('when checking multiple namespaces', () => { - const namespaces = [namespace1, namespace2]; - test(`throws an error when using an empty namespaces array`, async () => { const checkSavedObjectsPrivileges = createFactory(); @@ -58,6 +58,7 @@ describe('#checkSavedObjectsPrivileges', () => { mockCheckPrivileges.atSpaces.mockReturnValue(expectedResult as any); const checkSavedObjectsPrivileges = createFactory(); + const namespaces = [namespace1, namespace2]; const result = await checkSavedObjectsPrivileges(actions, namespaces); expect(result).toBe(expectedResult); @@ -70,6 +71,30 @@ describe('#checkSavedObjectsPrivileges', () => { const spaceIds = mockSpacesService!.namespaceToSpaceId.mock.results.map((x) => x.value); expect(mockCheckPrivileges.atSpaces).toHaveBeenCalledWith(spaceIds, actions); }); + + test(`de-duplicates namespaces`, async () => { + const expectedResult = Symbol(); + mockCheckPrivileges.atSpaces.mockReturnValue(expectedResult as any); + const checkSavedObjectsPrivileges = createFactory(); + + const namespaces = [undefined, 'default', namespace1, namespace1]; + const result = await checkSavedObjectsPrivileges(actions, namespaces); + + expect(result).toBe(expectedResult); + expect(mockSpacesService!.namespaceToSpaceId).toHaveBeenCalledTimes(4); + expect(mockSpacesService!.namespaceToSpaceId).toHaveBeenNthCalledWith(1, undefined); + expect(mockSpacesService!.namespaceToSpaceId).toHaveBeenNthCalledWith(2, 'default'); + expect(mockSpacesService!.namespaceToSpaceId).toHaveBeenNthCalledWith(3, namespace1); + expect(mockSpacesService!.namespaceToSpaceId).toHaveBeenNthCalledWith(4, namespace1); + expect(mockCheckPrivilegesWithRequest).toHaveBeenCalledTimes(1); + expect(mockCheckPrivilegesWithRequest).toHaveBeenCalledWith(request); + expect(mockCheckPrivileges.atSpaces).toHaveBeenCalledTimes(1); + const spaceIds = [ + mockSpacesService!.namespaceToSpaceId(undefined), // deduplicated with 'default' + mockSpacesService!.namespaceToSpaceId(namespace1), // deduplicated with namespace1 + ]; + expect(mockCheckPrivileges.atSpaces).toHaveBeenCalledWith(spaceIds, actions); + }); }); describe('when checking a single namespace', () => { diff --git a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts index 0c2260542bf72..6d2f724dae948 100644 --- a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts +++ b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts @@ -14,9 +14,13 @@ export type CheckSavedObjectsPrivilegesWithRequest = ( export type CheckSavedObjectsPrivileges = ( actions: string | string[], - namespaceOrNamespaces?: string | string[] + namespaceOrNamespaces?: string | Array ) => Promise; +function uniq(arr: T[]): T[] { + return Array.from(new Set(arr)); +} + export const checkSavedObjectsPrivilegesWithRequestFactory = ( checkPrivilegesWithRequest: CheckPrivilegesWithRequest, getSpacesService: () => SpacesService | undefined @@ -26,7 +30,7 @@ export const checkSavedObjectsPrivilegesWithRequestFactory = ( ): CheckSavedObjectsPrivileges { return async function checkSavedObjectsPrivileges( actions: string | string[], - namespaceOrNamespaces?: string | string[] + namespaceOrNamespaces?: string | Array ) { const spacesService = getSpacesService(); if (!spacesService) { @@ -37,7 +41,10 @@ export const checkSavedObjectsPrivilegesWithRequestFactory = ( if (!namespaceOrNamespaces.length) { throw new Error(`Can't check saved object privileges for 0 namespaces`); } - const spaceIds = namespaceOrNamespaces.map((x) => spacesService.namespaceToSpaceId(x)); + const spaceIds = uniq( + namespaceOrNamespaces.map((x) => spacesService.namespaceToSpaceId(x)) + ); + return await checkPrivilegesWithRequest(request).atSpaces(spaceIds, actions); } else { // Spaces enabled, authorizing against a single space diff --git a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts index 7f7f969e8b480..2cf072453a3c7 100644 --- a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts +++ b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts @@ -117,7 +117,11 @@ const expectSuccess = async (fn: Function, args: Record, action?: s return result; }; -const expectPrivilegeCheck = async (fn: Function, args: Record) => { +const expectPrivilegeCheck = async ( + fn: Function, + args: Record, + namespacesOverride?: Array +) => { clientOpts.checkSavedObjectsPrivilegesAsCurrentUser.mockImplementation( getMockCheckPrivilegesFailure ); @@ -131,7 +135,7 @@ const expectPrivilegeCheck = async (fn: Function, args: Record) => expect(clientOpts.checkSavedObjectsPrivilegesAsCurrentUser).toHaveBeenCalledTimes(1); expect(clientOpts.checkSavedObjectsPrivilegesAsCurrentUser).toHaveBeenCalledWith( actions, - args.options?.namespace ?? args.options?.namespaces + namespacesOverride ?? args.options?.namespace ?? args.options?.namespaces ); }; @@ -483,7 +487,18 @@ describe('#bulkUpdate', () => { test(`checks privileges for user, actions, and namespace`, async () => { const objects = [obj1, obj2]; - await expectPrivilegeCheck(client.bulkUpdate, { objects, options }); + const namespacesOverride = [options.namespace]; // the bulkCreate function checks privileges as an array + await expectPrivilegeCheck(client.bulkUpdate, { objects, options }, namespacesOverride); + }); + + test(`checks privileges for object namespaces if present`, async () => { + const objects = [ + { ...obj1, namespace: 'foo-ns' }, + { ...obj2, namespace: 'bar-ns' }, + ]; + const namespacesOverride = [undefined, 'foo-ns', 'bar-ns']; + // use the default namespace for the options + await expectPrivilegeCheck(client.bulkUpdate, { objects, options: {} }, namespacesOverride); }); test(`filters namespaces that the user doesn't have access to`, async () => { diff --git a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts index 68fe65d204d6d..bfa08a0116644 100644 --- a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts +++ b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts @@ -199,12 +199,16 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra objects: Array> = [], options: SavedObjectsBaseOptions = {} ) { - await this.ensureAuthorized( - this.getUniqueObjectTypes(objects), - 'bulk_update', - options && options.namespace, - { objects, options } - ); + const objectNamespaces = objects + // The repository treats an `undefined` object namespace is treated as the absence of a namespace, falling back to options.namespace; + // in this case, filter it out here so we don't accidentally check for privileges in the Default space when we shouldn't be doing so. + .filter(({ namespace }) => namespace !== undefined) + .map(({ namespace }) => namespace!); + const namespaces = [options?.namespace, ...objectNamespaces]; + await this.ensureAuthorized(this.getUniqueObjectTypes(objects), 'bulk_update', namespaces, { + objects, + options, + }); const response = await this.baseClient.bulkUpdate(objects, options); return await this.redactSavedObjectsNamespaces(response); @@ -212,7 +216,7 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra private async checkPrivileges( actions: string | string[], - namespaceOrNamespaces?: string | string[] + namespaceOrNamespaces?: string | Array ) { try { return await this.checkSavedObjectsPrivilegesAsCurrentUser(actions, namespaceOrNamespaces); @@ -224,7 +228,7 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra private async ensureAuthorized( typeOrTypes: string | string[], action: string, - namespaceOrNamespaces?: string | string[], + namespaceOrNamespaces?: string | Array, args?: Record, auditAction: string = action, requiresAll = true diff --git a/x-pack/plugins/security_solution/package.json b/x-pack/plugins/security_solution/package.json index 70dbaa0d31681..fd7941fb17cc5 100644 --- a/x-pack/plugins/security_solution/package.json +++ b/x-pack/plugins/security_solution/package.json @@ -9,7 +9,7 @@ "build-graphql-types": "node scripts/generate_types_from_graphql.js", "cypress:open": "cypress open --config-file ./cypress/cypress.json", "cypress:open-as-ci": "node ../../../scripts/functional_tests --config ../../test/security_solution_cypress/visual_config.ts", - "cypress:run": "cypress run --browser chrome --headless --spec ./cypress/integration/**/*.spec.ts --config-file ./cypress/cypress.json --reporter ../../node_modules/cypress-multi-reporters --reporter-options configFile=./cypress/reporter_config.json; status=$?; ../../node_modules/.bin/mochawesome-merge --reportDir ../../../target/kibana-security-solution/cypress/results > ../../../target/kibana-security-solution/cypress/results/output.json; ../../../node_modules/.bin/marge ../../../target/kibana-security-solution/cypress/results/output.json --reportDir ../../../target/kibana-security-solution/cypress/results; mkdir -p ../../../target/junit && cp ../../../target/kibana-security-solution/cypress/results/*.xml ../../../target/junit/ && exit $status;", + "cypress:run": "cypress run --browser chrome --headless --spec ./cypress/integration/**/*.spec.ts --config-file ./cypress/cypress.json --reporter ../../node_modules/cypress-multi-reporters --reporter-options configFile=./cypress/reporter_config.json; status=$?; ../../node_modules/.bin/mochawesome-merge ../../../target/kibana-security-solution/cypress/results/mochawesome*.json > ../../../target/kibana-security-solution/cypress/results/output.json; ../../../node_modules/.bin/marge ../../../target/kibana-security-solution/cypress/results/output.json --reportDir ../../../target/kibana-security-solution/cypress/results; mkdir -p ../../../target/junit && cp ../../../target/kibana-security-solution/cypress/results/*.xml ../../../target/junit/ && exit $status;", "cypress:run-as-ci": "node ../../../scripts/functional_tests --config ../../test/security_solution_cypress/cli_config.ts", "test:generate": "node scripts/endpoint/resolver_generator" }, diff --git a/x-pack/plugins/security_solution/public/cases/containers/configure/mock.ts b/x-pack/plugins/security_solution/public/cases/containers/configure/mock.ts index 9b9e978ffca4b..2fc761f4dc429 100644 --- a/x-pack/plugins/security_solution/public/cases/containers/configure/mock.ts +++ b/x-pack/plugins/security_solution/public/cases/containers/configure/mock.ts @@ -77,7 +77,7 @@ export const connectorsMock: Connector[] = [ name: 'Jira', config: { apiUrl: 'https://instance.atlassian.ne', - casesConfiguration: { + incidentConfiguration: { mapping: [ { source: 'title', diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/components/connector_flyout/index.tsx b/x-pack/plugins/security_solution/public/common/lib/connectors/components/connector_flyout/index.tsx deleted file mode 100644 index 30e2c650a70cc..0000000000000 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/components/connector_flyout/index.tsx +++ /dev/null @@ -1,157 +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, { useCallback, useEffect } from 'react'; -import { EuiFieldText, EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiSpacer } from '@elastic/eui'; - -import { isEmpty, get } from 'lodash/fp'; - -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { ActionConnectorFieldsProps } from '../../../../../../../triggers_actions_ui/public/types'; -import { FieldMapping } from '../../../../../cases/components/configure_cases/field_mapping'; - -import { CasesConfigurationMapping } from '../../../../../cases/containers/configure/types'; - -import * as i18n from '../../translations'; -import { ActionConnector, ConnectorFlyoutHOCProps } from '../../types'; -import { createDefaultMapping } from '../../utils'; -import { connectorsConfiguration } from '../../config'; - -export const withConnectorFlyout = ({ - ConnectorFormComponent, - connectorActionTypeId, - secretKeys = [], - configKeys = [], -}: ConnectorFlyoutHOCProps) => { - const ConnectorFlyout: React.FC> = ({ - action, - editActionConfig, - editActionSecrets, - errors, - }) => { - /* We do not provide defaults values to the fields (like empty string for apiUrl) intentionally. - * If we do, errors will be shown the first time the flyout is open even though the user did not - * interact with the form. Also, we would like to show errors for empty fields provided by the user. - /*/ - const { apiUrl, casesConfiguration: { mapping = [] } = {} } = action.config; - const configKeysWithDefault = [...configKeys, 'apiUrl']; - - const isApiUrlInvalid: boolean = errors.apiUrl.length > 0 && apiUrl != null; - - /** - * We need to distinguish between the add flyout and the edit flyout. - * useEffect will run only once on component mount. - * This guarantees that the function below will run only once. - * On the first render of the component the apiUrl can be either undefined or filled. - * If it is filled then we are on the edit flyout. Otherwise we are on the add flyout. - */ - - useEffect(() => { - if (!isEmpty(apiUrl)) { - secretKeys.forEach((key: string) => editActionSecrets(key, '')); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - if (isEmpty(mapping)) { - editActionConfig('casesConfiguration', { - ...action.config.casesConfiguration, - mapping: createDefaultMapping(connectorsConfiguration[connectorActionTypeId].fields), - }); - } - - const handleOnChangeActionConfig = useCallback( - (key: string, value: string) => editActionConfig(key, value), - // eslint-disable-next-line react-hooks/exhaustive-deps - [] - ); - - const handleOnBlurActionConfig = useCallback( - (key: string) => { - if (configKeysWithDefault.includes(key) && get(key, action.config) == null) { - editActionConfig(key, ''); - } - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [action.config] - ); - - const handleOnChangeSecretConfig = useCallback( - (key: string, value: string) => editActionSecrets(key, value), - // eslint-disable-next-line react-hooks/exhaustive-deps - [] - ); - - const handleOnBlurSecretConfig = useCallback( - (key: string) => { - if (secretKeys.includes(key) && get(key, action.secrets) == null) { - editActionSecrets(key, ''); - } - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [action.secrets] - ); - - const handleOnChangeMappingConfig = useCallback( - (newMapping: CasesConfigurationMapping[]) => - editActionConfig('casesConfiguration', { - ...action.config.casesConfiguration, - mapping: newMapping, - }), - // eslint-disable-next-line react-hooks/exhaustive-deps - [action.config] - ); - - return ( - <> - - - - handleOnChangeActionConfig('apiUrl', evt.target.value)} - onBlur={handleOnBlurActionConfig.bind(null, 'apiUrl')} - /> - - - - - - - - - - - - - ); - }; - - return ConnectorFlyout; -}; diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/config.ts b/x-pack/plugins/security_solution/public/common/lib/connectors/config.ts index 9e6982ea20301..3aca186378820 100644 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/config.ts +++ b/x-pack/plugins/security_solution/public/common/lib/connectors/config.ts @@ -9,12 +9,12 @@ import { ServiceNowConnectorConfiguration, JiraConnectorConfiguration, + ResilientConnectorConfiguration, } from '../../../../../triggers_actions_ui/public/common'; -import { connector as resilientConnectorConfig } from './resilient/config'; import { ConnectorConfiguration } from './types'; export const connectorsConfiguration: Record = { '.servicenow': ServiceNowConnectorConfiguration as ConnectorConfiguration, '.jira': JiraConnectorConfiguration as ConnectorConfiguration, - '.resilient': resilientConnectorConfig, + '.resilient': ResilientConnectorConfiguration as ConnectorConfiguration, }; diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/flyout.tsx b/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/flyout.tsx deleted file mode 100644 index 31bf0a4dfc34b..0000000000000 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/flyout.tsx +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import React from 'react'; -import { - EuiFieldText, - EuiFlexGroup, - EuiFlexItem, - EuiFormRow, - EuiFieldPassword, - EuiSpacer, -} from '@elastic/eui'; - -import * as i18n from './translations'; -import { ConnectorFlyoutFormProps } from '../types'; -import { ResilientActionConnector } from './types'; -import { withConnectorFlyout } from '../components/connector_flyout'; - -const resilientConnectorForm: React.FC> = ({ - errors, - action, - onChangeSecret, - onBlurSecret, - onChangeConfig, - onBlurConfig, -}) => { - const { orgId } = action.config; - const { apiKeyId, apiKeySecret } = action.secrets; - const isOrgIdInvalid: boolean = errors.orgId.length > 0 && orgId != null; - const isApiKeyIdInvalid: boolean = errors.apiKeyId.length > 0 && apiKeyId != null; - const isApiKeySecretInvalid: boolean = errors.apiKeySecret.length > 0 && apiKeySecret != null; - - return ( - <> - - - - onChangeConfig('orgId', evt.target.value)} - onBlur={() => onBlurConfig('orgId')} - /> - - - - - - - - onChangeSecret('apiKeyId', evt.target.value)} - onBlur={() => onBlurSecret('apiKeyId')} - /> - - - - - - - - onChangeSecret('apiKeySecret', evt.target.value)} - onBlur={() => onBlurSecret('apiKeySecret')} - /> - - - - - ); -}; - -export const resilientConnectorFlyout = withConnectorFlyout({ - ConnectorFormComponent: resilientConnectorForm, - secretKeys: ['apiKeyId', 'apiKeySecret'], - configKeys: ['orgId'], - connectorActionTypeId: '.resilient', -}); - -// eslint-disable-next-line import/no-default-export -export { resilientConnectorFlyout as default }; diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/index.tsx b/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/index.tsx deleted file mode 100644 index ba4879e87a1f6..0000000000000 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/index.tsx +++ /dev/null @@ -1,54 +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 { lazy } from 'react'; -import { - ValidationResult, - // eslint-disable-next-line @kbn/eslint/no-restricted-paths -} from '../../../../../../triggers_actions_ui/public/types'; - -import { connector } from './config'; -import { createActionType } from '../utils'; -import logo from './logo.svg'; -import { ResilientActionConnector } from './types'; -import * as i18n from './translations'; - -interface Errors { - orgId: string[]; - apiKeyId: string[]; - apiKeySecret: string[]; -} - -const validateConnector = (action: ResilientActionConnector): ValidationResult => { - const errors: Errors = { - orgId: [], - apiKeyId: [], - apiKeySecret: [], - }; - - if (!action.config.orgId) { - errors.orgId = [...errors.orgId, i18n.RESILIENT_PROJECT_KEY_REQUIRED]; - } - - if (!action.secrets.apiKeyId) { - errors.apiKeyId = [...errors.apiKeyId, i18n.RESILIENT_API_KEY_ID_REQUIRED]; - } - - if (!action.secrets.apiKeySecret) { - errors.apiKeySecret = [...errors.apiKeySecret, i18n.RESILIENT_API_KEY_SECRET_REQUIRED]; - } - - return { errors }; -}; - -export const getActionType = createActionType({ - id: connector.id, - iconClass: logo, - selectMessage: i18n.RESILIENT_DESC, - actionTypeTitle: connector.name, - validateConnector, - actionConnectorFields: lazy(() => import('./flyout')), -}); diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/translations.ts b/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/translations.ts deleted file mode 100644 index 2ff97ad354095..0000000000000 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/translations.ts +++ /dev/null @@ -1,72 +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 { i18n } from '@kbn/i18n'; - -export * from '../translations'; - -export const RESILIENT_DESC = i18n.translate( - 'xpack.securitySolution.case.connectors.resilient.selectMessageText', - { - defaultMessage: 'Push or update Security case data to a new issue in Resilient', - } -); - -export const RESILIENT_TITLE = i18n.translate( - 'xpack.securitySolution.case.connectors.resilient.actionTypeTitle', - { - defaultMessage: 'IBM Resilient', - } -); - -export const RESILIENT_PROJECT_KEY_LABEL = i18n.translate( - 'xpack.securitySolution.case.connectors.resilient.orgId', - { - defaultMessage: 'Organization ID', - } -); - -export const RESILIENT_PROJECT_KEY_REQUIRED = i18n.translate( - 'xpack.securitySolution.case.connectors.resilient.requiredOrgIdTextField', - { - defaultMessage: 'Organization ID is required', - } -); - -export const RESILIENT_API_KEY_ID_LABEL = i18n.translate( - 'xpack.securitySolution.case.connectors.resilient.apiKeyId', - { - defaultMessage: 'API key ID', - } -); - -export const RESILIENT_API_KEY_ID_REQUIRED = i18n.translate( - 'xpack.securitySolution.case.connectors.resilient.requiredApiKeyIdTextField', - { - defaultMessage: 'API key ID is required', - } -); - -export const RESILIENT_API_KEY_SECRET_LABEL = i18n.translate( - 'xpack.securitySolution.case.connectors.resilient.apiKeySecret', - { - defaultMessage: 'API key secret', - } -); - -export const RESILIENT_API_KEY_SECRET_REQUIRED = i18n.translate( - 'xpack.securitySolution.case.connectors.resilient.requiredApiKeySecretTextField', - { - defaultMessage: 'API key secret is required', - } -); - -export const MAPPING_FIELD_NAME = i18n.translate( - 'xpack.securitySolution.case.configureCases.mappingFieldName', - { - defaultMessage: 'Name', - } -); diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/types.ts b/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/types.ts deleted file mode 100644 index fe6dbb2b3674a..0000000000000 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/types.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -/* eslint-disable no-restricted-imports */ -/* eslint-disable @kbn/eslint/no-restricted-paths */ - -import { - ResilientPublicConfigurationType, - ResilientSecretConfigurationType, -} from '../../../../../../actions/server/builtin_action_types/resilient/types'; - -export { ResilientFieldsType } from '../../../../../../case/common/api/connectors'; - -export * from '../types'; - -export interface ResilientActionConnector { - config: ResilientPublicConfigurationType; - secrets: ResilientSecretConfigurationType; -} diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/translations.ts b/x-pack/plugins/security_solution/public/common/lib/connectors/translations.ts deleted file mode 100644 index 6dd1247d40fcb..0000000000000 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/translations.ts +++ /dev/null @@ -1,98 +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 { i18n } from '@kbn/i18n'; - -export const API_URL_LABEL = i18n.translate( - 'xpack.securitySolution.case.connectors.common.apiUrlTextFieldLabel', - { - defaultMessage: 'URL', - } -); - -export const API_URL_REQUIRED = i18n.translate( - 'xpack.securitySolution.case.connectors.common.requiredApiUrlTextField', - { - defaultMessage: 'URL is required', - } -); - -export const API_URL_INVALID = i18n.translate( - 'xpack.securitySolution.case.connectors.common.invalidApiUrlTextField', - { - defaultMessage: 'URL is invalid', - } -); - -export const USERNAME_LABEL = i18n.translate( - 'xpack.securitySolution.case.connectors.common.usernameTextFieldLabel', - { - defaultMessage: 'Username', - } -); - -export const USERNAME_REQUIRED = i18n.translate( - 'xpack.securitySolution.case.connectors.common.requiredUsernameTextField', - { - defaultMessage: 'Username is required', - } -); - -export const PASSWORD_LABEL = i18n.translate( - 'xpack.securitySolution.case.connectors.common.passwordTextFieldLabel', - { - defaultMessage: 'Password', - } -); - -export const PASSWORD_REQUIRED = i18n.translate( - 'xpack.securitySolution.case.connectors.common.requiredPasswordTextField', - { - defaultMessage: 'Password is required', - } -); - -export const API_TOKEN_LABEL = i18n.translate( - 'xpack.securitySolution.case.connectors.common.apiTokenTextFieldLabel', - { - defaultMessage: 'API token', - } -); - -export const API_TOKEN_REQUIRED = i18n.translate( - 'xpack.securitySolution.case.connectors.common.requiredApiTokenTextField', - { - defaultMessage: 'API token is required', - } -); - -export const EMAIL_LABEL = i18n.translate( - 'xpack.securitySolution.case.connectors.common.emailTextFieldLabel', - { - defaultMessage: 'Email', - } -); - -export const EMAIL_REQUIRED = i18n.translate( - 'xpack.securitySolution.case.connectors.common.requiredEmailTextField', - { - defaultMessage: 'Email is required', - } -); - -export const MAPPING_FIELD_DESC = i18n.translate( - 'xpack.securitySolution.case.configureCases.mappingFieldDescription', - { - defaultMessage: 'Description', - } -); - -export const MAPPING_FIELD_COMMENTS = i18n.translate( - 'xpack.securitySolution.case.configureCases.mappingFieldComments', - { - defaultMessage: 'Comments', - } -); diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/types.ts b/x-pack/plugins/security_solution/public/common/lib/connectors/types.ts index 1d688ad9b1d6a..5d83c226bfeca 100644 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/types.ts +++ b/x-pack/plugins/security_solution/public/common/lib/connectors/types.ts @@ -4,12 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -/* eslint-disable no-restricted-imports */ -/* eslint-disable @kbn/eslint/no-restricted-paths */ - import { ActionType } from '../../../../../triggers_actions_ui/public'; -import { IErrorObject } from '../../../../../triggers_actions_ui/public/types'; -import { ExternalIncidentServiceConfiguration } from '../../../../../actions/server/builtin_action_types/case/types'; import { ActionType as ThirdPartySupportedActions, @@ -29,34 +24,3 @@ export interface ConnectorConfiguration extends ActionType { logo: string; fields: Record; } - -export interface ActionConnector { - config: ExternalIncidentServiceConfiguration; - secrets: {}; -} - -export interface ActionConnectorParams { - message: string; -} - -export interface ActionConnectorValidationErrors { - apiUrl: string[]; -} - -export type Optional = Omit & Partial; - -export interface ConnectorFlyoutFormProps { - errors: IErrorObject; - action: T; - onChangeSecret: (key: string, value: string) => void; - onBlurSecret: (key: string) => void; - onChangeConfig: (key: string, value: string) => void; - onBlurConfig: (key: string) => void; -} - -export interface ConnectorFlyoutHOCProps { - ConnectorFormComponent: React.FC>; - connectorActionTypeId: string; - configKeys?: string[]; - secretKeys?: string[]; -} diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/utils.ts b/x-pack/plugins/security_solution/public/common/lib/connectors/utils.ts index 6e72205c145a2..0a6dd37d9f9e2 100644 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/utils.ts +++ b/x-pack/plugins/security_solution/public/common/lib/connectors/utils.ts @@ -4,63 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - ActionTypeModel, - ValidationResult, - // eslint-disable-next-line @kbn/eslint/no-restricted-paths -} from '../../../../../triggers_actions_ui/public/types'; - -import { - ActionConnector, - ActionConnectorParams, - ActionConnectorValidationErrors, - Optional, - ThirdPartyField, -} from './types'; -import { isUrlInvalid } from './validators'; - -import * as i18n from './translations'; import { CasesConfigurationMapping } from '../../../cases/containers/configure/types'; -export const createActionType = ({ - id, - actionTypeTitle, - selectMessage, - iconClass, - validateConnector, - validateParams = connectorParamsValidator, - actionConnectorFields, - actionParamsFields = null, -}: Optional) => (): ActionTypeModel => { - return { - id, - iconClass, - selectMessage, - actionTypeTitle, - validateConnector: (action: ActionConnector): ValidationResult => { - const errors: ActionConnectorValidationErrors = { - apiUrl: [], - }; - - if (!action.config.apiUrl) { - errors.apiUrl = [...errors.apiUrl, i18n.API_URL_REQUIRED]; - } - - if (isUrlInvalid(action.config.apiUrl)) { - errors.apiUrl = [...errors.apiUrl, i18n.API_URL_INVALID]; - } - - return { errors: { ...errors, ...validateConnector(action).errors } }; - }, - validateParams, - actionConnectorFields, - actionParamsFields, - }; -}; - -const connectorParamsValidator = (actionParams: ActionConnectorParams): ValidationResult => { - return { errors: {} }; -}; +import { ThirdPartyField } from './types'; export const createDefaultMapping = ( fields: Record diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/validators.ts b/x-pack/plugins/security_solution/public/common/lib/connectors/validators.ts deleted file mode 100644 index 2989cf4d98f85..0000000000000 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/validators.ts +++ /dev/null @@ -1,7 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -export { isUrlInvalid } from '../../utils/validators'; diff --git a/x-pack/plugins/security_solution/public/plugin.tsx b/x-pack/plugins/security_solution/public/plugin.tsx index 10bbbbfa72719..9b4eb6a25d1e5 100644 --- a/x-pack/plugins/security_solution/public/plugin.tsx +++ b/x-pack/plugins/security_solution/public/plugin.tsx @@ -21,7 +21,6 @@ import { import { Storage } from '../../../../src/plugins/kibana_utils/public'; import { initTelemetry } from './common/lib/telemetry'; import { KibanaServices } from './common/lib/kibana/services'; -import { resilientActionType } from './common/lib/connectors'; import { PluginSetup, PluginStart, @@ -96,8 +95,6 @@ export class Plugin implements IPlugin { const storage = new Storage(localStorage); const [coreStart, startPlugins] = await core.getStartServices(); diff --git a/x-pack/plugins/security_solution/public/resolver/view/assets.tsx b/x-pack/plugins/security_solution/public/resolver/view/assets.tsx index 6962d300f7072..1317c0ee94b60 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/assets.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/assets.tsx @@ -24,7 +24,8 @@ type ResolverColorNames = | 'resolverBackground' | 'resolverEdge' | 'resolverEdgeText' - | 'resolverBreadcrumbBackground'; + | 'resolverBreadcrumbBackground' + | 'pillStroke'; type ColorMap = Record; interface NodeStyleConfig { @@ -438,6 +439,7 @@ export const useResolverTheme = (): { resolverBreadcrumbBackground: theme.euiColorLightestShade, resolverEdgeText: getThemedOption(theme.euiColorDarkShade, theme.euiColorFullShade), triggerBackingFill: `${theme.euiColorDanger}${getThemedOption('0F', '1F')}`, + pillStroke: theme.euiColorLightShade, }; const nodeAssets: NodeStyleMap = { diff --git a/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx b/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx index 2aacc5f9176c4..5d7112dd1547a 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx @@ -38,6 +38,7 @@ const StyledActionsContainer = styled.div` position: absolute; top: ${(props) => `${props.topPct}%`}; width: auto; + pointer-events: all; `; interface StyledDescriptionText { @@ -61,6 +62,11 @@ const StyledDescriptionText = styled.div` width: fit-content; `; +const StyledOuterGroup = styled.g` + fill: none; + pointer-events: visiblePainted; +`; + /** * An artifact that represents a process node and the things associated with it in the Resolver */ @@ -329,6 +335,7 @@ const UnstyledProcessEventDot = React.memo( } role="img" aria-labelledby={labelHTMLID} + fill="none" style={{ display: 'block', width: '100%', @@ -338,9 +345,10 @@ const UnstyledProcessEventDot = React.memo( left: '0', outline: 'transparent', border: 'none', + pointerEvents: 'none', }} > - + - + unknown; @@ -52,73 +43,51 @@ interface ResolverSubmenuOption { export type ResolverSubmenuOptionList = ResolverSubmenuOption[] | string; -const OptionListItem = styled.div` - width: 175px; +const StyledActionButton = styled(EuiButton)` + &.euiButton--small { + height: fit-content; + line-height: 1; + padding: 0.25em; + font-size: 0.85rem; + } `; -const OptionList = React.memo( +/** + * This will be the "host button" that displays the "total number of related events" and opens + * the sumbmenu (with counts by category) when clicked. + */ +const SubButton = React.memo( ({ - subMenuOptions, - isLoading, + hasMenu, + menuIsOpen, + action, + count, + title, + nodeID, }: { - subMenuOptions: ResolverSubmenuOptionList; - isLoading: boolean; + hasMenu: boolean; + menuIsOpen?: boolean; + action: (evt: React.MouseEvent) => void; + count?: number; + title: string; + nodeID: string; }) => { - const [options, setOptions] = useState(() => - typeof subMenuOptions !== 'object' - ? [] - : subMenuOptions.map((option: ResolverSubmenuOption) => { - const dataTestSubj = 'resolver:map:node-submenu-item'; - return option.prefix - ? { - label: option.optionTitle, - prepend: {option.prefix} , - 'data-test-subj': dataTestSubj, - } - : { - label: option.optionTitle, - prepend: , - 'data-test-subj': dataTestSubj, - }; - }) - ); - - const actionsByLabel: Record unknown> = useMemo(() => { - if (typeof subMenuOptions !== 'object') { - return {}; - } - return subMenuOptions.reduce((titleActionRecord, opt) => { - const { optionTitle, action } = opt; - return { ...titleActionRecord, [optionTitle]: action }; - }, {}); - }, [subMenuOptions]); - - const selectableProps = useMemo(() => { - return { - listProps: { showIcons: true, bordered: true }, - onChange: (newOptions: EuiSelectableOption[]) => { - const selectedOption = newOptions.find((opt) => opt.checked === 'on'); - if (selectedOption) { - const { label } = selectedOption; - const actionToTake = actionsByLabel[label]; - if (typeof actionToTake === 'function') { - actionToTake(); - } - } - setOptions(newOptions); - }, - }; - }, [actionsByLabel]); - + const iconType = menuIsOpen === true ? 'arrowUp' : 'arrowDown'; return ( - - {(list) => {list}} - + {count ? : ''} {title} + ); } ); @@ -177,11 +146,6 @@ const NodeSubMenuComponents = React.memo( [menuAction] ); - const closePopover = useCallback(() => setMenuOpen(false), []); - const popoverId = idGenerator('submenu-popover'); - - const isMenuLoading = optionsWithActions === 'waitingForRelatedEventData'; - // The last projection matrix that was used to position the popover const projectionMatrixAtLastRender = useRef(); @@ -204,6 +168,16 @@ const NodeSubMenuComponents = React.memo( projectionMatrixAtLastRender.current = projectionMatrix; }, [projectionMatrixAtLastRender, projectionMatrix]); + const { + colorMap: { pillStroke: pillBorderStroke, resolverBackground: pillFill }, + } = useResolverTheme(); + const listStylesFromTheme = useMemo(() => { + return { + border: `1.5px solid ${pillBorderStroke}`, + backgroundColor: pillFill, + }; + }, [pillBorderStroke, pillFill]); + if (!optionsWithActions) { /** * When called with a `menuAction` @@ -222,44 +196,47 @@ const NodeSubMenuComponents = React.memo( ); } - /** - * When called with a set of `optionsWithActions`: - * Render with a panel of options that appear when the menu host button is clicked - */ - const submenuPopoverButton = ( - - {count ? : ''} {menuTitle} - - ); + if (typeof optionsWithActions === 'string') { + return <>; + } return ( -
- - {menuIsOpen && typeof optionsWithActions === 'object' && ( - - )} - -
+ <> + + {menuIsOpen ? ( +
    + {optionsWithActions + .sort((opta, optb) => { + return opta.optionTitle.localeCompare(optb.optionTitle); + }) + .map((opt) => { + return ( +
  • + +
  • + ); + })} +
+ ) : null} + ); } ); @@ -271,6 +248,48 @@ export const NodeSubMenu = styled(NodeSubMenuComponents)` display: flex; flex-flow: column; + &.options { + font-size: 0.8rem; + display: flex; + flex-flow: row wrap; + background: transparent; + position: absolute; + top: 6.5em; + contain: content; + width: 12em; + z-index: 2; + } + + &.options .item { + margin: 0.25ch 0.35ch 0.35ch 0; + padding: 0.35em 0.5em; + height: fit-content; + width: fit-content; + border-radius: 2px; + line-height: 0.8; + } + + &.options .item button { + appearance: none; + height: fit-content; + width: fit-content; + line-height: 0.8; + outline-style: none; + border-color: transparent; + box-shadow: none; + } + + &.options .item button:focus { + outline-style: none; + border-color: transparent; + box-shadow: none; + text-decoration: underline; + } + + &.options .item button:active { + transform: scale(0.95); + } + & .euiButton { background-color: ${(props) => props.buttonFill}; border-color: ${(props) => props.buttonBorderColor}; @@ -283,16 +302,4 @@ export const NodeSubMenu = styled(NodeSubMenuComponents)` background-color: ${(props) => props.buttonFill}; } } - - & .euiPopover__anchor { - display: flex; - } - - &.is-open .euiButton { - border-bottom-left-radius: 0; - border-bottom-right-radius: 0; - } - &.is-open .euiSelectableListItem__prepend { - color: white; - } `; diff --git a/x-pack/plugins/spaces/server/lib/copy_to_spaces/copy_to_spaces.test.ts b/x-pack/plugins/spaces/server/lib/copy_to_spaces/copy_to_spaces.test.ts index d49dfa2015dc6..1cec7b769fa26 100644 --- a/x-pack/plugins/spaces/server/lib/copy_to_spaces/copy_to_spaces.test.ts +++ b/x-pack/plugins/spaces/server/lib/copy_to_spaces/copy_to_spaces.test.ts @@ -20,6 +20,7 @@ import { copySavedObjectsToSpacesFactory } from './copy_to_spaces'; jest.mock('../../../../../../src/core/server', () => { return { + ...(jest.requireActual('../../../../../../src/core/server') as Record), exportSavedObjectsToStream: jest.fn(), importSavedObjectsFromStream: jest.fn(), }; diff --git a/x-pack/plugins/spaces/server/lib/copy_to_spaces/resolve_copy_conflicts.test.ts b/x-pack/plugins/spaces/server/lib/copy_to_spaces/resolve_copy_conflicts.test.ts index 6a77bf7397cb5..37181c9d81649 100644 --- a/x-pack/plugins/spaces/server/lib/copy_to_spaces/resolve_copy_conflicts.test.ts +++ b/x-pack/plugins/spaces/server/lib/copy_to_spaces/resolve_copy_conflicts.test.ts @@ -20,6 +20,7 @@ import { resolveCopySavedObjectsToSpacesConflictsFactory } from './resolve_copy_ jest.mock('../../../../../../src/core/server', () => { return { + ...(jest.requireActual('../../../../../../src/core/server') as Record), exportSavedObjectsToStream: jest.fn(), resolveSavedObjectsImportErrors: jest.fn(), }; diff --git a/x-pack/plugins/spaces/server/lib/utils/__mocks__/index.ts b/x-pack/plugins/spaces/server/lib/utils/__mocks__/index.ts new file mode 100644 index 0000000000000..2b93e6d87a7af --- /dev/null +++ b/x-pack/plugins/spaces/server/lib/utils/__mocks__/index.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. + */ + +const mockNamespaceIdToString = jest.fn(); +const mockNamespaceStringToId = jest.fn(); +jest.mock('../../../../../../../src/core/server', () => ({ + SavedObjectsUtils: { + namespaceIdToString: mockNamespaceIdToString, + namespaceStringToId: mockNamespaceStringToId, + }, +})); + +export { mockNamespaceIdToString, mockNamespaceStringToId }; diff --git a/x-pack/plugins/spaces/server/lib/utils/namespace.test.ts b/x-pack/plugins/spaces/server/lib/utils/namespace.test.ts index a81a5f3cee187..79d3dda301045 100644 --- a/x-pack/plugins/spaces/server/lib/utils/namespace.test.ts +++ b/x-pack/plugins/spaces/server/lib/utils/namespace.test.ts @@ -4,45 +4,29 @@ * you may not use this file except in compliance with the Elastic License. */ -import { DEFAULT_SPACE_ID } from '../../../common/constants'; +import { mockNamespaceIdToString, mockNamespaceStringToId } from './__mocks__'; import { spaceIdToNamespace, namespaceToSpaceId } from './namespace'; -describe('#spaceIdToNamespace', () => { - it('converts the default space to undefined', () => { - expect(spaceIdToNamespace(DEFAULT_SPACE_ID)).toBeUndefined(); - }); - - it('returns non-default spaces as-is', () => { - expect(spaceIdToNamespace('foo')).toEqual('foo'); - }); - - it('throws an error when a spaceId is not provided', () => { - // @ts-ignore ts knows this isn't right - expect(() => spaceIdToNamespace()).toThrowErrorMatchingInlineSnapshot(`"spaceId is required"`); +beforeEach(() => { + jest.clearAllMocks(); +}); - // @ts-ignore ts knows this isn't right - expect(() => spaceIdToNamespace(null)).toThrowErrorMatchingInlineSnapshot( - `"spaceId is required"` - ); +describe('#spaceIdToNamespace', () => { + it('returns result of namespaceStringToId', () => { + mockNamespaceStringToId.mockReturnValue('bar'); - expect(() => spaceIdToNamespace('')).toThrowErrorMatchingInlineSnapshot( - `"spaceId is required"` - ); + const result = spaceIdToNamespace('foo'); + expect(mockNamespaceStringToId).toHaveBeenCalledWith('foo'); + expect(result).toEqual('bar'); }); }); describe('#namespaceToSpaceId', () => { - it('returns the default space id for undefined namespaces', () => { - expect(namespaceToSpaceId(undefined)).toEqual(DEFAULT_SPACE_ID); - }); - - it('returns all other namespaces as-is', () => { - expect(namespaceToSpaceId('foo')).toEqual('foo'); - }); + it('returns result of namespaceIdToString', () => { + mockNamespaceIdToString.mockReturnValue('bar'); - it('throws an error when an empty string is provided', () => { - expect(() => namespaceToSpaceId('')).toThrowErrorMatchingInlineSnapshot( - `"namespace cannot be an empty string"` - ); + const result = namespaceToSpaceId('foo'); + expect(mockNamespaceIdToString).toHaveBeenCalledWith('foo'); + expect(result).toEqual('bar'); }); }); diff --git a/x-pack/plugins/spaces/server/lib/utils/namespace.ts b/x-pack/plugins/spaces/server/lib/utils/namespace.ts index 8c7ed2ea1797d..344da18846f3b 100644 --- a/x-pack/plugins/spaces/server/lib/utils/namespace.ts +++ b/x-pack/plugins/spaces/server/lib/utils/namespace.ts @@ -4,28 +4,22 @@ * you may not use this file except in compliance with the Elastic License. */ -import { DEFAULT_SPACE_ID } from '../../../common/constants'; +import { SavedObjectsUtils } from '../../../../../../src/core/server'; -export function spaceIdToNamespace(spaceId: string): string | undefined { - if (!spaceId) { - throw new TypeError('spaceId is required'); - } - - if (spaceId === DEFAULT_SPACE_ID) { - return undefined; - } - - return spaceId; +/** + * Converts a Space ID string to its namespace ID representation. Note that a Space ID string is equivalent to a namespace string. + * + * See also: {@link namespaceStringToId}. + */ +export function spaceIdToNamespace(spaceId: string) { + return SavedObjectsUtils.namespaceStringToId(spaceId); } -export function namespaceToSpaceId(namespace: string | undefined): string { - if (namespace === '') { - throw new TypeError('namespace cannot be an empty string'); - } - - if (!namespace) { - return DEFAULT_SPACE_ID; - } - - return namespace; +/** + * Converts a namespace ID to its Space ID string representation. Note that a Space ID string is equivalent to a namespace string. + * + * See also: {@link namespaceIdToString}. + */ +export function namespaceToSpaceId(namespace?: string) { + return SavedObjectsUtils.namespaceIdToString(namespace); } diff --git a/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.test.ts b/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.test.ts index bec3a5dcb0b71..dce6de908cfcb 100644 --- a/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.test.ts +++ b/x-pack/plugins/spaces/server/routes/api/external/copy_to_space.test.ts @@ -30,10 +30,10 @@ import { securityMock } from '../../../../../security/server/mocks'; import { ObjectType } from '@kbn/config-schema'; jest.mock('../../../../../../../src/core/server', () => { return { + ...(jest.requireActual('../../../../../../../src/core/server') as Record), exportSavedObjectsToStream: jest.fn(), importSavedObjectsFromStream: jest.fn(), resolveSavedObjectsImportErrors: jest.fn(), - kibanaResponseFactory: jest.requireActual('src/core/server').kibanaResponseFactory, }; }); import { diff --git a/x-pack/plugins/transform/common/utils/errors.ts b/x-pack/plugins/transform/common/utils/errors.ts new file mode 100644 index 0000000000000..0c31d7e1584f0 --- /dev/null +++ b/x-pack/plugins/transform/common/utils/errors.ts @@ -0,0 +1,31 @@ +/* + * 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 interface ErrorResponse { + body: { + statusCode: number; + error: string; + message: string; + attributes?: any; + }; + name: string; +} + +export function isErrorResponse(arg: any): arg is ErrorResponse { + return arg?.body?.error !== undefined && arg?.body?.message !== undefined; +} + +export function getErrorMessage(error: any) { + if (isErrorResponse(error)) { + return `${error.body.error}: ${error.body.message}`; + } + + if (typeof error === 'object' && typeof error.message === 'string') { + return error.message; + } + + return JSON.stringify(error); +} diff --git a/x-pack/plugins/transform/public/__mocks__/shared_imports.ts b/x-pack/plugins/transform/public/__mocks__/shared_imports.ts index e115e086f45b5..f7441fd93f38a 100644 --- a/x-pack/plugins/transform/public/__mocks__/shared_imports.ts +++ b/x-pack/plugins/transform/public/__mocks__/shared_imports.ts @@ -15,7 +15,6 @@ export const useRequest = jest.fn(() => ({ // just passing through the reimports export { - getErrorMessage, getDataGridSchemaFromKibanaFieldType, getFieldsFromKibanaIndexPattern, multiColumnSortFactory, diff --git a/x-pack/plugins/transform/public/app/hooks/use_delete_transform.tsx b/x-pack/plugins/transform/public/app/hooks/use_delete_transform.tsx index 43c5ae6fad1b1..fdf77c8ebee51 100644 --- a/x-pack/plugins/transform/public/app/hooks/use_delete_transform.tsx +++ b/x-pack/plugins/transform/public/app/hooks/use_delete_transform.tsx @@ -12,7 +12,8 @@ import { DeleteTransformStatus, TransformEndpointRequest, } from '../../../common'; -import { extractErrorMessage, getErrorMessage } from '../../shared_imports'; +import { extractErrorMessage } from '../../shared_imports'; +import { getErrorMessage } from '../../../common/utils/errors'; import { useAppDependencies, useToastNotifications } from '../app_dependencies'; import { REFRESH_TRANSFORM_LIST_STATE, refreshTransformList$, TransformListRow } from '../common'; import { ToastNotificationText } from '../components'; diff --git a/x-pack/plugins/transform/public/app/hooks/use_index_data.ts b/x-pack/plugins/transform/public/app/hooks/use_index_data.ts index ad5850f26be2e..946f7991d049d 100644 --- a/x-pack/plugins/transform/public/app/hooks/use_index_data.ts +++ b/x-pack/plugins/transform/public/app/hooks/use_index_data.ts @@ -12,7 +12,6 @@ import { getFieldType, getDataGridSchemaFromKibanaFieldType, getFieldsFromKibanaIndexPattern, - getErrorMessage, showDataGridColumnChartErrorMessageToast, useDataGrid, useRenderCellValue, @@ -21,6 +20,7 @@ import { UseIndexDataReturnType, INDEX_STATUS, } from '../../shared_imports'; +import { getErrorMessage } from '../../../common/utils/errors'; import { isDefaultQuery, matchAllQuery, PivotQuery } from '../common'; diff --git a/x-pack/plugins/transform/public/app/hooks/use_pivot_data.ts b/x-pack/plugins/transform/public/app/hooks/use_pivot_data.ts index a9f34996b9b51..a0e7c5dde494a 100644 --- a/x-pack/plugins/transform/public/app/hooks/use_pivot_data.ts +++ b/x-pack/plugins/transform/public/app/hooks/use_pivot_data.ts @@ -18,13 +18,13 @@ import { formatHumanReadableDateTimeSeconds } from '../../shared_imports'; import { getNestedProperty } from '../../../common/utils/object_utils'; import { - getErrorMessage, multiColumnSortFactory, useDataGrid, RenderCellValue, UseIndexDataReturnType, INDEX_STATUS, } from '../../shared_imports'; +import { getErrorMessage } from '../../../common/utils/errors'; import { getPreviewRequestBody, diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_create/step_create_form.tsx b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_create/step_create_form.tsx index 255a245081d5a..2fa1b7c713370 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_create/step_create_form.tsx +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_create/step_create_form.tsx @@ -32,7 +32,7 @@ import { toMountPoint } from '../../../../../../../../../src/plugins/kibana_reac import { PROGRESS_REFRESH_INTERVAL_MS } from '../../../../../../common/constants'; -import { getErrorMessage } from '../../../../../shared_imports'; +import { getErrorMessage } from '../../../../../../common/utils/errors'; import { getTransformProgress, getDiscoverUrl } from '../../../../common'; import { useApi } from '../../../../hooks/use_api'; diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_details/step_details_form.tsx b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_details/step_details_form.tsx index 271fde27f519a..85f4065e8c069 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_details/step_details_form.tsx +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_details/step_details_form.tsx @@ -16,7 +16,7 @@ import { toMountPoint } from '../../../../../../../../../src/plugins/kibana_reac import { TransformId } from '../../../../../../common'; import { isValidIndexName } from '../../../../../../common/utils/es_utils'; -import { getErrorMessage } from '../../../../../shared_imports'; +import { getErrorMessage } from '../../../../../../common/utils/errors'; import { useAppDependencies, useToastNotifications } from '../../../../app_dependencies'; import { ToastNotificationText } from '../../../../components'; diff --git a/x-pack/plugins/transform/public/app/sections/transform_management/components/edit_transform_flyout/edit_transform_flyout.tsx b/x-pack/plugins/transform/public/app/sections/transform_management/components/edit_transform_flyout/edit_transform_flyout.tsx index 77a7ae25ce887..735a059e57e14 100644 --- a/x-pack/plugins/transform/public/app/sections/transform_management/components/edit_transform_flyout/edit_transform_flyout.tsx +++ b/x-pack/plugins/transform/public/app/sections/transform_management/components/edit_transform_flyout/edit_transform_flyout.tsx @@ -23,7 +23,7 @@ import { EuiTitle, } from '@elastic/eui'; -import { getErrorMessage } from '../../../../../shared_imports'; +import { getErrorMessage } from '../../../../../../common/utils/errors'; import { refreshTransformList$, diff --git a/x-pack/plugins/transform/public/shared_imports.ts b/x-pack/plugins/transform/public/shared_imports.ts index abbc39dd6c728..196df250b7a3d 100644 --- a/x-pack/plugins/transform/public/shared_imports.ts +++ b/x-pack/plugins/transform/public/shared_imports.ts @@ -15,7 +15,6 @@ export { export { getFieldType, - getErrorMessage, extractErrorMessage, formatHumanReadableDateTimeSeconds, getDataGridSchemaFromKibanaFieldType, diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 7fb9b7ef64143..74b13acee7b58 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -816,8 +816,6 @@ "data.query.queryBar.KQLNestedQuerySyntaxInfoTitle": "KQL ネストされたクエリ構文", "data.query.queryBar.kqlOffLabel": "オフ", "data.query.queryBar.kqlOnLabel": "オン", - "data.query.queryBar.licenseOptions": "ライセンスオプションに進む", - "data.query.queryBar.longQueryMessage": "ライセンスをアップグレードすれば、リクエストの完了までに十分な時間を確保できます。", "data.query.queryBar.luceneLanguageName": "Lucene", "data.query.queryBar.luceneSyntaxWarningMessage": "Lucene クエリ構文を使用しているようですが、Kibana クエリ言語 (KQL) が選択されています。KQL ドキュメント {link} を確認してください。", "data.query.queryBar.luceneSyntaxWarningOptOutText": "今後表示しない", @@ -6676,8 +6674,6 @@ "xpack.data.kueryAutocomplete.lessThanOrEqualOperatorDescription.lessThanOrEqualToText": "より小さいまたは等しい", "xpack.data.kueryAutocomplete.orOperatorDescription": "{oneOrMoreArguments} が true であることを条件とする", "xpack.data.kueryAutocomplete.orOperatorDescription.oneOrMoreArgumentsText": "1つ以上の引数", - "xpack.data.query.queryBar.cancelLongQuery": "キャンセル", - "xpack.data.query.queryBar.runBeyond": "タイムアウトを越えて実行", "xpack.discover.FlyoutCreateDrilldownAction.displayName": "基本データを調査", "xpack.embeddableEnhanced.actions.panelNotifications.manyDrilldowns": "パネルには{count}個のドリルダウンがあります", "xpack.embeddableEnhanced.actions.panelNotifications.oneDrilldown": "パネルには1個のドリルダウンがあります", @@ -10887,7 +10883,6 @@ "xpack.ml.dataframe.analyticsList.deleteAnalyticsErrorMessage": "データフレーム分析ジョブ{analyticsId}の削除中にエラーが発生しました。", "xpack.ml.dataframe.analyticsList.deleteAnalyticsPrivilegeErrorMessage": "ユーザーはインデックス{indexName}を削除する権限がありません。{error}", "xpack.ml.dataframe.analyticsList.deleteAnalyticsSuccessMessage": "データフレーム分析ジョブ{analyticsId}の削除リクエストが受け付けられました。", - "xpack.ml.dataframe.analyticsList.deleteAnalyticsWithIndexErrorMessage": "ディスティネーションインデックス{destinationIndex}の削除中にエラーが発生しました。{error}", "xpack.ml.dataframe.analyticsList.deleteAnalyticsWithIndexPatternErrorMessage": "インデックスパターン{destinationIndex}の削除中にエラーが発生しました。{error}", "xpack.ml.dataframe.analyticsList.deleteAnalyticsWithIndexPatternSuccessMessage": "インデックスパターン{destinationIndex}を削除する要求が確認されました。", "xpack.ml.dataframe.analyticsList.deleteAnalyticsWithIndexSuccessMessage": "ディスティネーションインデックス{destinationIndex}を削除する要求が確認されました。", @@ -11355,16 +11350,9 @@ "xpack.ml.jobService.activeDatafeedsLabel": "アクティブなデータフィード", "xpack.ml.jobService.activeMLNodesLabel": "アクティブな ML ノード", "xpack.ml.jobService.closedJobsLabel": "ジョブを作成", - "xpack.ml.jobService.couldNotStartDatafeedErrorMessage": "{jobId} のデータフィードを開始できませんでした", - "xpack.ml.jobService.couldNotStopDatafeedErrorMessage": "{jobId} のデータフィードを停止できませんでした", - "xpack.ml.jobService.couldNotUpdateDatafeedErrorMessage": "データフィードを更新できませんでした: {datafeedId}", - "xpack.ml.jobService.datafeedsListCouldNotBeRetrievedErrorMessage": "データフィードリストを取得できませんでした", "xpack.ml.jobService.failedJobsLabel": "失敗したジョブ", - "xpack.ml.jobService.jobsListCouldNotBeRetrievedErrorMessage": "ジョブリストを取得できませんでした", "xpack.ml.jobService.openJobsLabel": "ジョブを開く", - "xpack.ml.jobService.requestMayHaveTimedOutErrorMessage": "リクエストがタイムアウトし、まだバックグラウンドで実行中の可能性があります。", "xpack.ml.jobService.totalJobsLabel": "合計ジョブ数", - "xpack.ml.jobService.updateJobErrorTitle": "ジョブを更新できませんでした: {jobId}", "xpack.ml.jobService.validateJobErrorTitle": "ジョブ検証エラー", "xpack.ml.jobsList.actionExecuteSuccessfullyNotificationMessage": "{successesJobsCount, plural, one{{successJob}} other{# 件のジョブ}} {actionTextPT}成功", "xpack.ml.jobsList.actionFailedNotificationMessage": "{failureId} が {actionText} に失敗しました", @@ -11569,7 +11557,6 @@ "xpack.ml.maxFileSizeSettingsDescription": "ファイルデータビジュアライザーでデータをインポートするときのファイルサイズ上限を設定します。この設定でサポートされている最大値は1 GBです。", "xpack.ml.maxFileSizeSettingsError": "200 MB、1 GBなどの有効なデータサイズにしてください。", "xpack.ml.maxFileSizeSettingsName": "ファイルデータビジュアライザーの最大ファイルアップロードサイズ", - "xpack.ml.messagebarService.errorTitle": "エラーが発生しました", "xpack.ml.models.jobService.allOtherRequestsCancelledDescription": " 他のすべてのリクエストはキャンセルされました。", "xpack.ml.models.jobService.categorization.messages.failureToGetTokens": "フィールド値の例のサンプルをトークン化することができませんでした。{message}", "xpack.ml.models.jobService.categorization.messages.insufficientPrivileges": "権限が不十分なため、フィールド値の例のトークン化を実行できませんでした。そのため、フィールド値を確認し、カテゴリー分けジョブでの使用が適当かを確認することができません。", @@ -15104,9 +15091,6 @@ "xpack.securitySolution.case.configureCases.incidentManagementSystemDesc": "オプションとして、セキュリティケースを選択した外部のインシデント管理システムに接続できます。そうすると、選択したサードパーティシステム内でケースデータをインシデントとしてプッシュできます。", "xpack.securitySolution.case.configureCases.incidentManagementSystemLabel": "インシデント管理システム", "xpack.securitySolution.case.configureCases.incidentManagementSystemTitle": "外部のインシデント管理システムに接続", - "xpack.securitySolution.case.configureCases.mappingFieldComments": "コメント", - "xpack.securitySolution.case.configureCases.mappingFieldDescription": "説明", - "xpack.securitySolution.case.configureCases.mappingFieldName": "名前", "xpack.securitySolution.case.configureCases.mappingFieldNotMapped": "マップされません", "xpack.securitySolution.case.configureCases.noConnector": "コネクターを選択していません", "xpack.securitySolution.case.configureCases.updateConnector": "コネクターを更新", @@ -15120,25 +15104,6 @@ "xpack.securitySolution.case.confirmDeleteCase.deleteCases": "ケースを削除", "xpack.securitySolution.case.confirmDeleteCase.deleteTitle": "「{caseTitle}」を削除", "xpack.securitySolution.case.confirmDeleteCase.selectedCases": "選択したケースを削除", - "xpack.securitySolution.case.connectors.common.apiTokenTextFieldLabel": "APIトークン", - "xpack.securitySolution.case.connectors.common.apiUrlTextFieldLabel": "URL", - "xpack.securitySolution.case.connectors.common.emailTextFieldLabel": "メール", - "xpack.securitySolution.case.connectors.common.invalidApiUrlTextField": "URLが無効です", - "xpack.securitySolution.case.connectors.common.passwordTextFieldLabel": "パスワード", - "xpack.securitySolution.case.connectors.common.requiredApiTokenTextField": "APIトークンが必要です", - "xpack.securitySolution.case.connectors.common.requiredApiUrlTextField": "URLが必要です", - "xpack.securitySolution.case.connectors.common.requiredEmailTextField": "電子メールが必要です", - "xpack.securitySolution.case.connectors.common.requiredPasswordTextField": "パスワードが必要です", - "xpack.securitySolution.case.connectors.common.requiredUsernameTextField": "ユーザー名が必要です", - "xpack.securitySolution.case.connectors.common.usernameTextFieldLabel": "ユーザー名", - "xpack.securitySolution.case.connectors.resilient.actionTypeTitle": "IBM Resilient", - "xpack.securitySolution.case.connectors.resilient.apiKeyId": "APIキーID", - "xpack.securitySolution.case.connectors.resilient.apiKeySecret": "APIキーシークレット", - "xpack.securitySolution.case.connectors.resilient.orgId": "組織ID", - "xpack.securitySolution.case.connectors.resilient.requiredApiKeyIdTextField": "APIキーIDが必要です", - "xpack.securitySolution.case.connectors.resilient.requiredApiKeySecretTextField": "APIキーシークレットが必要です", - "xpack.securitySolution.case.connectors.resilient.requiredOrgIdTextField": "組織IDが必要です", - "xpack.securitySolution.case.connectors.resilient.selectMessageText": "Resilientでセキュリティケースデータを更新するか、新しいインシデントにプッシュ", "xpack.securitySolution.case.createCase.descriptionFieldRequiredError": "説明が必要です。", "xpack.securitySolution.case.createCase.fieldTagsHelpText": "このケースの1つ以上のカスタム識別タグを入力します。新しいタグを開始するには、各タグの後でEnterを押します。", "xpack.securitySolution.case.createCase.titleFieldRequiredError": "タイトルが必要です。", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index c217f8819f978..75e225fe34611 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -817,8 +817,6 @@ "data.query.queryBar.KQLNestedQuerySyntaxInfoTitle": "KQL 嵌套查询语法", "data.query.queryBar.kqlOffLabel": "关闭", "data.query.queryBar.kqlOnLabel": "开启", - "data.query.queryBar.licenseOptions": "前往许可证选项", - "data.query.queryBar.longQueryMessage": "使用升级的许可证,您可以确保有足够的时间来完成请求。", "data.query.queryBar.luceneLanguageName": "Lucene", "data.query.queryBar.luceneSyntaxWarningMessage": "尽管您选择了 Kibana 查询语言 (KQL),但似乎您正在尝试使用 Lucene 查询语法。请查看 KQL 文档 {link}。", "data.query.queryBar.luceneSyntaxWarningOptOutText": "不再显示", @@ -6679,8 +6677,6 @@ "xpack.data.kueryAutocomplete.lessThanOrEqualOperatorDescription.lessThanOrEqualToText": "小于或等于", "xpack.data.kueryAutocomplete.orOperatorDescription": "需要{oneOrMoreArguments}为 true", "xpack.data.kueryAutocomplete.orOperatorDescription.oneOrMoreArgumentsText": "一个或多个参数", - "xpack.data.query.queryBar.cancelLongQuery": "取消", - "xpack.data.query.queryBar.runBeyond": "运行超时", "xpack.discover.FlyoutCreateDrilldownAction.displayName": "浏览底层数据", "xpack.embeddableEnhanced.actions.panelNotifications.manyDrilldowns": "面板有 {count} 个向下钻取", "xpack.embeddableEnhanced.actions.panelNotifications.oneDrilldown": "面板有 1 个向下钻取", @@ -10893,7 +10889,6 @@ "xpack.ml.dataframe.analyticsList.deleteAnalyticsErrorMessage": "删除数据帧分析作业 {analyticsId} 时发生错误", "xpack.ml.dataframe.analyticsList.deleteAnalyticsPrivilegeErrorMessage": "用户无权删除索引 {indexName}:{error}", "xpack.ml.dataframe.analyticsList.deleteAnalyticsSuccessMessage": "删除的数据帧分析作业 {analyticsId} 的请求已确认。", - "xpack.ml.dataframe.analyticsList.deleteAnalyticsWithIndexErrorMessage": "删除目标索引 {destinationIndex} 时发生错误:{error}", "xpack.ml.dataframe.analyticsList.deleteAnalyticsWithIndexPatternErrorMessage": "删除索引模式 {destinationIndex} 时发生错误:{error}", "xpack.ml.dataframe.analyticsList.deleteAnalyticsWithIndexPatternSuccessMessage": "删除索引模式 {destinationIndex} 的请求已确认。", "xpack.ml.dataframe.analyticsList.deleteAnalyticsWithIndexSuccessMessage": "删除目标索引 {destinationIndex} 的请求已确认。", @@ -11362,16 +11357,9 @@ "xpack.ml.jobService.activeDatafeedsLabel": "活动数据馈送", "xpack.ml.jobService.activeMLNodesLabel": "活动 ML 节点", "xpack.ml.jobService.closedJobsLabel": "已关闭的作业", - "xpack.ml.jobService.couldNotStartDatafeedErrorMessage": "无法开始 {jobId} 的数据馈送", - "xpack.ml.jobService.couldNotStopDatafeedErrorMessage": "无法停止 {jobId} 的数据馈送", - "xpack.ml.jobService.couldNotUpdateDatafeedErrorMessage": "无法更新数据馈送:{datafeedId}", - "xpack.ml.jobService.datafeedsListCouldNotBeRetrievedErrorMessage": "无法检索数据馈送列表", "xpack.ml.jobService.failedJobsLabel": "失败的作业", - "xpack.ml.jobService.jobsListCouldNotBeRetrievedErrorMessage": "无法检索作业列表", "xpack.ml.jobService.openJobsLabel": "打开的作业", - "xpack.ml.jobService.requestMayHaveTimedOutErrorMessage": "请求可能已超时,并可能仍在后台运行。", "xpack.ml.jobService.totalJobsLabel": "总计作业数", - "xpack.ml.jobService.updateJobErrorTitle": "无法更新作业:{jobId}", "xpack.ml.jobService.validateJobErrorTitle": "作业验证错误", "xpack.ml.jobsList.actionExecuteSuccessfullyNotificationMessage": "{successesJobsCount, plural, one{{successJob}} other{# 个作业}}{actionTextPT}已成功", "xpack.ml.jobsList.actionFailedNotificationMessage": "{failureId} 未能{actionText}", @@ -11576,7 +11564,6 @@ "xpack.ml.maxFileSizeSettingsDescription": "设置在文件数据可视化工具中导入数据时的文件大小限制。此设置支持的最高值为 1GB。", "xpack.ml.maxFileSizeSettingsError": "应为有效的数据大小。如 200MB、1GB", "xpack.ml.maxFileSizeSettingsName": "文件数据可视化工具最大文件上传大小", - "xpack.ml.messagebarService.errorTitle": "发生了错误", "xpack.ml.models.jobService.allOtherRequestsCancelledDescription": " 所有其他请求已取消。", "xpack.ml.models.jobService.categorization.messages.failureToGetTokens": "无法对示例字段值样本进行分词。{message}", "xpack.ml.models.jobService.categorization.messages.insufficientPrivileges": "由于权限不足,无法对字段值示例执行分词。因此,无法检查字段值是否适合用于归类作业。", @@ -15113,9 +15100,6 @@ "xpack.securitySolution.case.configureCases.incidentManagementSystemDesc": "您可能会根据需要将 Security 案例连接到选择的外部事件管理系统。这将允许您将案例数据作为事件推送到所选第三方系统。", "xpack.securitySolution.case.configureCases.incidentManagementSystemLabel": "事件管理系统", "xpack.securitySolution.case.configureCases.incidentManagementSystemTitle": "连接到外部事件管理系统", - "xpack.securitySolution.case.configureCases.mappingFieldComments": "注释", - "xpack.securitySolution.case.configureCases.mappingFieldDescription": "描述", - "xpack.securitySolution.case.configureCases.mappingFieldName": "名称", "xpack.securitySolution.case.configureCases.mappingFieldNotMapped": "未映射", "xpack.securitySolution.case.configureCases.noConnector": "未选择连接器", "xpack.securitySolution.case.configureCases.updateConnector": "更新连接器", @@ -15129,25 +15113,6 @@ "xpack.securitySolution.case.confirmDeleteCase.deleteCases": "删除案例", "xpack.securitySolution.case.confirmDeleteCase.deleteTitle": "删除“{caseTitle}”", "xpack.securitySolution.case.confirmDeleteCase.selectedCases": "删除选定案例", - "xpack.securitySolution.case.connectors.common.apiTokenTextFieldLabel": "API 令牌", - "xpack.securitySolution.case.connectors.common.apiUrlTextFieldLabel": "URL", - "xpack.securitySolution.case.connectors.common.emailTextFieldLabel": "电子邮件", - "xpack.securitySolution.case.connectors.common.invalidApiUrlTextField": "URL 无效", - "xpack.securitySolution.case.connectors.common.passwordTextFieldLabel": "密码", - "xpack.securitySolution.case.connectors.common.requiredApiTokenTextField": "“API 令牌”必填", - "xpack.securitySolution.case.connectors.common.requiredApiUrlTextField": "“URL”必填", - "xpack.securitySolution.case.connectors.common.requiredEmailTextField": "“电子邮件”必填", - "xpack.securitySolution.case.connectors.common.requiredPasswordTextField": "“密码”必填", - "xpack.securitySolution.case.connectors.common.requiredUsernameTextField": "“用户名”必填", - "xpack.securitySolution.case.connectors.common.usernameTextFieldLabel": "用户名", - "xpack.securitySolution.case.connectors.resilient.actionTypeTitle": "IBM Resilient", - "xpack.securitySolution.case.connectors.resilient.apiKeyId": "API 密钥 ID", - "xpack.securitySolution.case.connectors.resilient.apiKeySecret": "API 密钥密码", - "xpack.securitySolution.case.connectors.resilient.orgId": "组织 ID", - "xpack.securitySolution.case.connectors.resilient.requiredApiKeyIdTextField": "“API 密钥 ID”必填", - "xpack.securitySolution.case.connectors.resilient.requiredApiKeySecretTextField": "“API 密钥密码”必填", - "xpack.securitySolution.case.connectors.resilient.requiredOrgIdTextField": "“组织 ID”必填", - "xpack.securitySolution.case.connectors.resilient.selectMessageText": "将 Security 案例数据推送或更新到 Resilient 中的新问题", "xpack.securitySolution.case.createCase.descriptionFieldRequiredError": "描述必填。", "xpack.securitySolution.case.createCase.fieldTagsHelpText": "为此案例键入一个或多个定制识别标记。在每个标记后按 Enter 键可开始新的标记。", "xpack.securitySolution.case.createCase.titleFieldRequiredError": "标题必填。", diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_params.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_params.test.tsx index be3e8a31820c4..8c37dc940a238 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_params.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/email/email_params.test.tsx @@ -27,6 +27,7 @@ describe('EmailParamsFields renders', () => { docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} /> ); + expect(wrapper.find('[data-test-subj="toEmailAddressInput"]').length > 0).toBeTruthy(); expect( wrapper.find('[data-test-subj="toEmailAddressInput"]').first().prop('selectedOptions') diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_params.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_params.test.tsx index 25c04bda3f536..a882e3bc43f34 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_params.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_params.test.tsx @@ -13,6 +13,7 @@ describe('IndexParamsFields renders', () => { const actionParams = { documents: [{ test: 123 }], }; + const wrapper = mountWithIntl( { group: 'group', class: 'test class', }; + const wrapper = mountWithIntl( > { + return await http.post(`${BASE_ACTION_API_PATH}/action/${connectorId}/_execute`, { + body: JSON.stringify({ + params: { subAction: 'incidentTypes', subActionParams: {} }, + }), + signal, + }); +} + +export async function getSeverity({ + http, + signal, + connectorId, +}: { + http: HttpSetup; + signal: AbortSignal; + connectorId: string; +}): Promise> { + return await http.post(`${BASE_ACTION_API_PATH}/action/${connectorId}/_execute`, { + body: JSON.stringify({ + params: { subAction: 'severity', subActionParams: {} }, + }), + signal, + }); +} diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/config.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/config.ts similarity index 88% rename from x-pack/plugins/security_solution/public/common/lib/connectors/resilient/config.ts rename to x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/config.ts index 7d4edbf624877..a2054585c19b8 100644 --- a/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/config.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/config.ts @@ -4,14 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ConnectorConfiguration } from './types'; - import * as i18n from './translations'; import logo from './logo.svg'; -export const connector: ConnectorConfiguration = { +export const connectorConfiguration = { id: '.resilient', - name: i18n.RESILIENT_TITLE, + name: i18n.TITLE, logo, enabled: true, enabledInConfig: true, diff --git a/x-pack/plugins/ml/public/application/components/messagebar/index.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/index.ts similarity index 77% rename from x-pack/plugins/ml/public/application/components/messagebar/index.ts rename to x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/index.ts index 35130d28a890d..0905bd29493e7 100644 --- a/x-pack/plugins/ml/public/application/components/messagebar/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { mlMessageBarService } from './messagebar_service'; +export { getActionType as getResilientActionType } from './resilient'; diff --git a/x-pack/plugins/security_solution/public/common/lib/connectors/resilient/logo.svg b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/logo.svg similarity index 100% rename from x-pack/plugins/security_solution/public/common/lib/connectors/resilient/logo.svg rename to x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/logo.svg diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.test.tsx new file mode 100644 index 0000000000000..b73eb72f137c1 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.test.tsx @@ -0,0 +1,100 @@ +/* + * 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 { TypeRegistry } from '../../../type_registry'; +import { registerBuiltInActionTypes } from '.././index'; +import { ActionTypeModel } from '../../../../types'; +import { ResilientActionConnector } from './types'; + +const ACTION_TYPE_ID = '.resilient'; +let actionTypeModel: ActionTypeModel; + +beforeAll(() => { + const actionTypeRegistry = new TypeRegistry(); + registerBuiltInActionTypes({ actionTypeRegistry }); + const getResult = actionTypeRegistry.get(ACTION_TYPE_ID); + if (getResult !== null) { + actionTypeModel = getResult; + } +}); + +describe('actionTypeRegistry.get() works', () => { + test('action type static data is as expected', () => { + expect(actionTypeModel.id).toEqual(ACTION_TYPE_ID); + }); +}); + +describe('resilient connector validation', () => { + test('connector validation succeeds when connector config is valid', () => { + const actionConnector = { + secrets: { + apiKeyId: 'email', + apiKeySecret: 'token', + }, + id: 'test', + actionTypeId: '.resilient', + isPreconfigured: false, + name: 'resilient', + config: { + apiUrl: 'https://test/', + orgId: '201', + }, + } as ResilientActionConnector; + + expect(actionTypeModel.validateConnector(actionConnector)).toEqual({ + errors: { + apiUrl: [], + apiKeyId: [], + apiKeySecret: [], + orgId: [], + }, + }); + }); + + test('connector validation fails when connector config is not valid', () => { + const actionConnector = ({ + secrets: { + apiKeyId: 'user', + }, + id: '.jira', + actionTypeId: '.jira', + name: 'jira', + config: {}, + } as unknown) as ResilientActionConnector; + + expect(actionTypeModel.validateConnector(actionConnector)).toEqual({ + errors: { + apiUrl: ['URL is required.'], + apiKeyId: [], + apiKeySecret: ['API key secret is required'], + orgId: ['Organization ID is required'], + }, + }); + }); +}); + +describe('resilient action params validation', () => { + test('action params validation succeeds when action params is valid', () => { + const actionParams = { + subActionParams: { title: 'some title {{test}}' }, + }; + + expect(actionTypeModel.validateParams(actionParams)).toEqual({ + errors: { title: [] }, + }); + }); + + test('params validation fails when body is not valid', () => { + const actionParams = { + subActionParams: { title: '' }, + }; + + expect(actionTypeModel.validateParams(actionParams)).toEqual({ + errors: { + title: ['Title is required.'], + }, + }); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.tsx new file mode 100644 index 0000000000000..cda6935f3b73d --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient.tsx @@ -0,0 +1,69 @@ +/* + * 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 { lazy } from 'react'; +import { ValidationResult, ActionTypeModel } from '../../../../types'; +import { connectorConfiguration } from './config'; +import logo from './logo.svg'; +import { ResilientActionConnector, ResilientActionParams } from './types'; +import * as i18n from './translations'; +import { isValidUrl } from '../../../lib/value_validators'; + +const validateConnector = (action: ResilientActionConnector): ValidationResult => { + const validationResult = { errors: {} }; + const errors = { + apiUrl: new Array(), + orgId: new Array(), + apiKeyId: new Array(), + apiKeySecret: new Array(), + }; + validationResult.errors = errors; + + if (!action.config.apiUrl) { + errors.apiUrl = [...errors.apiUrl, i18n.API_URL_REQUIRED]; + } + + if (action.config.apiUrl && !isValidUrl(action.config.apiUrl, 'https:')) { + errors.apiUrl = [...errors.apiUrl, i18n.API_URL_INVALID]; + } + + if (!action.config.orgId) { + errors.orgId = [...errors.orgId, i18n.ORG_ID_REQUIRED]; + } + + if (!action.secrets.apiKeyId) { + errors.apiKeyId = [...errors.apiKeyId, i18n.API_KEY_ID_REQUIRED]; + } + + if (!action.secrets.apiKeySecret) { + errors.apiKeySecret = [...errors.apiKeySecret, i18n.API_KEY_SECRET_REQUIRED]; + } + + return validationResult; +}; + +export function getActionType(): ActionTypeModel { + return { + id: connectorConfiguration.id, + iconClass: logo, + selectMessage: i18n.DESC, + actionTypeTitle: connectorConfiguration.name, + validateConnector, + actionConnectorFields: lazy(() => import('./resilient_connectors')), + validateParams: (actionParams: ResilientActionParams): ValidationResult => { + const validationResult = { errors: {} }; + const errors = { + title: new Array(), + }; + validationResult.errors = errors; + if (actionParams.subActionParams && !actionParams.subActionParams.title?.length) { + errors.title.push(i18n.TITLE_REQUIRED); + } + return validationResult; + }, + actionParamsFields: lazy(() => import('./resilient_params')), + }; +} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.test.tsx new file mode 100644 index 0000000000000..7e242f1f501d8 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.test.tsx @@ -0,0 +1,100 @@ +/* + * 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 { mountWithIntl } from 'test_utils/enzyme_helpers'; +import { DocLinksStart } from 'kibana/public'; +import ResilientConnectorFields from './resilient_connectors'; +import { ResilientActionConnector } from './types'; + +describe('ResilientActionConnectorFields renders', () => { + test('alerting Resilient connector fields is rendered', () => { + const actionConnector = { + secrets: { + apiKeyId: 'key', + apiKeySecret: 'secret', + }, + id: 'test', + actionTypeId: '.resilient', + isPreconfigured: false, + name: 'resilient', + config: { + apiUrl: 'https://test/', + orgId: '201', + }, + } as ResilientActionConnector; + const deps = { + docLinks: { ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart, + }; + const wrapper = mountWithIntl( + {}} + editActionSecrets={() => {}} + docLinks={deps!.docLinks} + readOnly={false} + /> + ); + + expect(wrapper.find('[data-test-subj="apiUrlFromInput"]').length > 0).toBeTruthy(); + expect( + wrapper.find('[data-test-subj="connector-resilient-orgId-form-input"]').length > 0 + ).toBeTruthy(); + + expect( + wrapper.find('[data-test-subj="connector-resilient-apiKeySecret-form-input"]').length > 0 + ).toBeTruthy(); + + expect( + wrapper.find('[data-test-subj="connector-resilient-apiKeySecret-form-input"]').length > 0 + ).toBeTruthy(); + }); + + test('case specific Resilient connector fields is rendered', () => { + const actionConnector = { + secrets: { + apiKeyId: 'email', + apiKeySecret: 'token', + }, + id: 'test', + actionTypeId: '.resilient', + isPreconfigured: false, + name: 'resilient', + config: { + apiUrl: 'https://test/', + orgId: '201', + }, + } as ResilientActionConnector; + const deps = { + docLinks: { ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart, + }; + const wrapper = mountWithIntl( + {}} + editActionSecrets={() => {}} + docLinks={deps!.docLinks} + readOnly={false} + consumer={'case'} + /> + ); + + expect(wrapper.find('[data-test-subj="case-resilient-mappings"]').length > 0).toBeTruthy(); + expect(wrapper.find('[data-test-subj="apiUrlFromInput"]').length > 0).toBeTruthy(); + expect( + wrapper.find('[data-test-subj="connector-resilient-orgId-form-input"]').length > 0 + ).toBeTruthy(); + + expect( + wrapper.find('[data-test-subj="connector-resilient-apiKeySecret-form-input"]').length > 0 + ).toBeTruthy(); + + expect( + wrapper.find('[data-test-subj="connector-resilient-apiKeySecret-form-input"]').length > 0 + ).toBeTruthy(); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.tsx new file mode 100644 index 0000000000000..7965e216f1d6c --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_connectors.tsx @@ -0,0 +1,209 @@ +/* + * 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 } from 'react'; + +import { + EuiFieldText, + EuiFlexGroup, + EuiFlexItem, + EuiFormRow, + EuiFieldPassword, + EuiSpacer, +} from '@elastic/eui'; + +import { isEmpty } from 'lodash'; +import { ActionConnectorFieldsProps } from '../../../../types'; +import * as i18n from './translations'; +import { ResilientActionConnector } from './types'; +import { connectorConfiguration } from './config'; +import { FieldMapping, CasesConfigurationMapping, createDefaultMapping } from '../case_mappings'; + +const ResilientConnectorFields: React.FC> = ({ + action, + editActionSecrets, + editActionConfig, + errors, + consumer, + readOnly, + docLinks, +}) => { + // TODO: remove incidentConfiguration later, when Case Resilient will move their fields to the level of action execution + const { apiUrl, orgId, incidentConfiguration, isCaseOwned } = action.config; + const mapping = incidentConfiguration ? incidentConfiguration.mapping : []; + + const isApiUrlInvalid: boolean = errors.apiUrl.length > 0 && apiUrl != null; + + const { apiKeyId, apiKeySecret } = action.secrets; + + const isOrgIdInvalid: boolean = errors.orgId.length > 0 && orgId != null; + const isApiKeyInvalid: boolean = errors.apiKeyId.length > 0 && apiKeyId != null; + const isApiKeySecretInvalid: boolean = errors.apiKeySecret.length > 0 && apiKeySecret != null; + + // TODO: remove this block later, when Case ServiceNow will move their fields to the level of action execution + if (consumer === 'case') { + if (isEmpty(mapping)) { + editActionConfig('incidentConfiguration', { + mapping: createDefaultMapping(connectorConfiguration.fields as any), + }); + } + + if (!isCaseOwned) { + editActionConfig('isCaseOwned', true); + } + } + + const handleOnChangeActionConfig = useCallback( + (key: string, value: string) => editActionConfig(key, value), + // eslint-disable-next-line react-hooks/exhaustive-deps + [] + ); + + const handleOnChangeSecretConfig = useCallback( + (key: string, value: string) => editActionSecrets(key, value), + // eslint-disable-next-line react-hooks/exhaustive-deps + [] + ); + + const handleOnChangeMappingConfig = useCallback( + (newMapping: CasesConfigurationMapping[]) => + editActionConfig('incidentConfiguration', { + ...action.config.incidentConfiguration, + mapping: newMapping, + }), + // eslint-disable-next-line react-hooks/exhaustive-deps + [action.config] + ); + + return ( + <> + + + + handleOnChangeActionConfig('apiUrl', evt.target.value)} + onBlur={() => { + if (!apiUrl) { + editActionConfig('apiUrl', ''); + } + }} + /> + + + + + + + + handleOnChangeActionConfig('orgId', evt.target.value)} + onBlur={() => { + if (!orgId) { + editActionConfig('orgId', ''); + } + }} + /> + + + + + + + + handleOnChangeSecretConfig('apiKeyId', evt.target.value)} + onBlur={() => { + if (!apiKeyId) { + editActionSecrets('apiKeyId', ''); + } + }} + /> + + + + + + + + handleOnChangeSecretConfig('apiKeySecret', evt.target.value)} + onBlur={() => { + if (!apiKeySecret) { + editActionSecrets('apiKeySecret', ''); + } + }} + /> + + + + {consumer === 'case' && ( // TODO: remove this block later, when Case Resilient will move their fields to the level of action execution + <> + + + + + + + + )} + + ); +}; + +// eslint-disable-next-line import/no-default-export +export { ResilientConnectorFields as default }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.test.tsx new file mode 100644 index 0000000000000..17020805757f9 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.test.tsx @@ -0,0 +1,189 @@ +/* + * 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 { mountWithIntl } from 'test_utils/enzyme_helpers'; +import ResilientParamsFields from './resilient_params'; +import { DocLinksStart } from 'kibana/public'; + +import { useGetIncidentTypes } from './use_get_incident_types'; +import { useGetSeverity } from './use_get_severity'; + +jest.mock('../../../app_context', () => { + const post = jest.fn(); + return { + useAppDependencies: jest.fn(() => ({ http: { post } })), + }; +}); + +jest.mock('./use_get_incident_types'); +jest.mock('./use_get_severity'); + +const useGetIncidentTypesMock = useGetIncidentTypes as jest.Mock; +const useGetSeverityMock = useGetSeverity as jest.Mock; + +const actionParams = { + subAction: 'pushToService', + subActionParams: { + title: 'title', + description: 'some description', + comments: [{ commentId: '1', comment: 'comment for resilient' }], + incidentTypes: [1001], + severityCode: 6, + savedObjectId: '123', + externalId: null, + }, +}; +const connector = { + secrets: {}, + config: {}, + id: 'test', + actionTypeId: '.test', + name: 'Test', + isPreconfigured: false, +}; + +describe('ResilientParamsFields renders', () => { + const useGetIncidentTypesResponse = { + isLoading: false, + incidentTypes: [ + { + id: 19, + name: 'Malware', + }, + { + id: 21, + name: 'Denial of Service', + }, + ], + }; + + const useGetSeverityResponse = { + isLoading: false, + severity: [ + { + id: 4, + name: 'Low', + }, + { + id: 5, + name: 'Medium', + }, + { + id: 6, + name: 'High', + }, + ], + }; + + beforeEach(() => { + useGetIncidentTypesMock.mockReturnValue(useGetIncidentTypesResponse); + useGetSeverityMock.mockReturnValue(useGetSeverityResponse); + }); + + test('all params fields are rendered', () => { + const wrapper = mountWithIntl( + {}} + index={0} + messageVariables={[]} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} + actionConnector={connector} + /> + ); + expect(wrapper.find('[data-test-subj="incidentTypeComboBox"]').exists()).toBeTruthy(); + expect(wrapper.find('[data-test-subj="severitySelect"]').first().prop('value')).toStrictEqual( + 6 + ); + expect(wrapper.find('[data-test-subj="titleInput"]').length > 0).toBeTruthy(); + expect(wrapper.find('[data-test-subj="descriptionTextArea"]').length > 0).toBeTruthy(); + expect(wrapper.find('[data-test-subj="commentsTextArea"]').length > 0).toBeTruthy(); + }); + + test('it shows loading when loading incident types', () => { + useGetIncidentTypesMock.mockReturnValue({ ...useGetIncidentTypesResponse, isLoading: true }); + const wrapper = mountWithIntl( + {}} + index={0} + messageVariables={[]} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} + actionConnector={connector} + /> + ); + + expect( + wrapper.find('[data-test-subj="incidentTypeComboBox"]').first().prop('isLoading') + ).toBeTruthy(); + }); + + test('it shows loading when loading severity', () => { + useGetSeverityMock.mockReturnValue({ + ...useGetSeverityResponse, + isLoading: true, + }); + + const wrapper = mountWithIntl( + {}} + index={0} + messageVariables={[]} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} + actionConnector={connector} + /> + ); + + expect( + wrapper.find('[data-test-subj="severitySelect"]').first().prop('isLoading') + ).toBeTruthy(); + }); + + test('it disabled the fields when loading issue types', () => { + useGetIncidentTypesMock.mockReturnValue({ ...useGetIncidentTypesResponse, isLoading: true }); + + const wrapper = mountWithIntl( + {}} + index={0} + messageVariables={[]} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} + actionConnector={connector} + /> + ); + + expect( + wrapper.find('[data-test-subj="incidentTypeComboBox"]').first().prop('isDisabled') + ).toBeTruthy(); + }); + + test('it disabled the fields when loading severity', () => { + useGetSeverityMock.mockReturnValue({ + ...useGetSeverityResponse, + isLoading: true, + }); + + const wrapper = mountWithIntl( + {}} + index={0} + messageVariables={[]} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} + actionConnector={connector} + /> + ); + + expect(wrapper.find('[data-test-subj="severitySelect"]').first().prop('disabled')).toBeTruthy(); + }); +}); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.tsx new file mode 100644 index 0000000000000..4b157c6999985 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/resilient_params.tsx @@ -0,0 +1,256 @@ +/* + * 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, { Fragment, useEffect, useState } from 'react'; +import { + EuiFormRow, + EuiComboBox, + EuiSelect, + EuiSpacer, + EuiTitle, + EuiComboBoxOptionOption, + EuiSelectOption, +} from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; + +import { ActionParamsProps } from '../../../../types'; +import { useAppDependencies } from '../../../app_context'; +import { ResilientActionParams } from './types'; +import { TextAreaWithMessageVariables } from '../../text_area_with_message_variables'; +import { TextFieldWithMessageVariables } from '../../text_field_with_message_variables'; + +import { useGetIncidentTypes } from './use_get_incident_types'; +import { useGetSeverity } from './use_get_severity'; + +const ResilientParamsFields: React.FunctionComponent> = ({ + actionParams, + editAction, + index, + errors, + messageVariables, + actionConnector, +}) => { + const [firstLoad, setFirstLoad] = useState(false); + const { http, toastNotifications } = useAppDependencies(); + const { title, description, comments, incidentTypes, severityCode, savedObjectId } = + actionParams.subActionParams || {}; + + const [incidentTypesComboBoxOptions, setIncidentTypesComboBoxOptions] = useState< + Array> + >([]); + + const [selectedIncidentTypesComboBoxOptions, setSelectedIncidentTypesComboBoxOptions] = useState< + Array> + >([]); + + const [severitySelectOptions, setSeveritySelectOptions] = useState([]); + + useEffect(() => { + setFirstLoad(true); + }, []); + + const { + isLoading: isLoadingIncidentTypes, + incidentTypes: allIncidentTypes, + } = useGetIncidentTypes({ + http, + toastNotifications, + actionConnector, + }); + + const { isLoading: isLoadingSeverity, severity } = useGetSeverity({ + http, + toastNotifications, + actionConnector, + }); + + const editSubActionProperty = (key: string, value: {}) => { + const newProps = { ...actionParams.subActionParams, [key]: value }; + editAction('subActionParams', newProps, index); + }; + + useEffect(() => { + const options = severity.map((s) => ({ + value: s.id.toString(), + text: s.name, + })); + + setSeveritySelectOptions(options); + }, [actionConnector, severity]); + + // Reset parameters when changing connector + useEffect(() => { + if (!firstLoad) { + return; + } + + setIncidentTypesComboBoxOptions([]); + setSelectedIncidentTypesComboBoxOptions([]); + setSeveritySelectOptions([]); + editAction('subActionParams', { title, comments, description: '', savedObjectId }, index); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [actionConnector]); + + useEffect(() => { + if (!actionParams.subAction) { + editAction('subAction', 'pushToService', index); + } + if (!savedObjectId && messageVariables?.find((variable) => variable.name === 'alertId')) { + editSubActionProperty('savedObjectId', '{{alertId}}'); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [actionConnector, savedObjectId]); + + useEffect(() => { + setIncidentTypesComboBoxOptions( + allIncidentTypes + ? allIncidentTypes.map((type: { id: number; name: string }) => ({ + label: type.name, + value: type.id.toString(), + })) + : [] + ); + + const allIncidentTypesAsObject = allIncidentTypes.reduce( + (acc, type) => ({ ...acc, [type.id.toString()]: type.name }), + {} as Record + ); + + setSelectedIncidentTypesComboBoxOptions( + incidentTypes + ? incidentTypes + .map((type) => ({ + label: allIncidentTypesAsObject[type.toString()], + value: type.toString(), + })) + .filter((type) => type.label != null) + : [] + ); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [actionConnector, allIncidentTypes]); + + return ( + + +

Incident

+
+ + + ) => { + setSelectedIncidentTypesComboBoxOptions( + selectedOptions.map((selectedOption) => ({ + label: selectedOption.label, + value: selectedOption.value, + })) + ); + + editSubActionProperty( + 'incidentTypes', + selectedOptions.map((selectedOption) => selectedOption.value ?? selectedOption.label) + ); + }} + onBlur={() => { + if (!incidentTypes) { + editSubActionProperty('incidentTypes', []); + } + }} + isClearable={true} + /> + + + + { + editSubActionProperty('severityCode', e.target.value); + }} + /> + + + 0 && title !== undefined} + label={i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.titleFieldLabel', + { + defaultMessage: 'Name', + } + )} + > + + + + { + editSubActionProperty(key, [{ commentId: 'alert-comment', comment: value }]); + }} + messageVariables={messageVariables} + paramsProperty={'comments'} + inputTargetValue={comments && comments.length > 0 ? comments[0].comment : ''} + label={i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.commentsTextAreaFieldLabel', + { + defaultMessage: 'Additional comments (optional)', + } + )} + errors={errors.comments as string[]} + /> +
+ ); +}; + +// eslint-disable-next-line import/no-default-export +export { ResilientParamsFields as default }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/translations.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/translations.ts new file mode 100644 index 0000000000000..71ad05abfdecf --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/translations.ts @@ -0,0 +1,133 @@ +/* + * 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 DESC = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.selectMessageText', + { + defaultMessage: 'Push or update data to a new incident in Resilient.', + } +); + +export const TITLE = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.actionTypeTitle', + { + defaultMessage: 'Resilient', + } +); + +export const API_URL_LABEL = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiUrlTextFieldLabel', + { + defaultMessage: 'URL', + } +); + +export const API_URL_REQUIRED = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.requiredApiUrlTextField', + { + defaultMessage: 'URL is required.', + } +); + +export const API_URL_INVALID = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.invalidApiUrlTextField', + { + defaultMessage: 'URL is invalid.', + } +); + +export const ORG_ID_LABEL = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.orgId', + { + defaultMessage: 'Organization ID', + } +); + +export const ORG_ID_REQUIRED = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.requiredOrgIdTextField', + { + defaultMessage: 'Organization ID is required', + } +); + +export const API_KEY_ID_LABEL = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiKeyId', + { + defaultMessage: 'API key ID', + } +); + +export const API_KEY_ID_REQUIRED = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.requiredApiKeyIdTextField', + { + defaultMessage: 'API key ID is required', + } +); + +export const API_KEY_SECRET_LABEL = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.apiKeySecret', + { + defaultMessage: 'API key secret', + } +); + +export const API_KEY_SECRET_REQUIRED = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.requiredApiKeySecretTextField', + { + defaultMessage: 'API key secret is required', + } +); + +export const MAPPING_FIELD_NAME = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.mappingFieldShortDescription', + { + defaultMessage: 'Name', + } +); + +export const MAPPING_FIELD_DESC = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.mappingFieldDescription', + { + defaultMessage: 'Description', + } +); + +export const MAPPING_FIELD_COMMENTS = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.mappingFieldComments', + { + defaultMessage: 'Comments', + } +); + +export const DESCRIPTION_REQUIRED = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.common.requiredDescriptionTextField', + { + defaultMessage: 'Description is required.', + } +); + +export const TITLE_REQUIRED = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.common.requiredTitleTextField', + { + defaultMessage: 'Title is required.', + } +); + +export const INCIDENT_TYPES_API_ERROR = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.unableToGetIncidentTypesMessage', + { + defaultMessage: 'Unable to get incident types', + } +); + +export const SEVERITY_API_ERROR = i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.resilient.unableToGetSeverityMessage', + { + defaultMessage: 'Unable to get severity', + } +); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/types.ts b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/types.ts new file mode 100644 index 0000000000000..37516f5bac372 --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/types.ts @@ -0,0 +1,41 @@ +/* + * 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 { CasesConfigurationMapping } from '../case_mappings'; + +export interface ResilientActionConnector { + config: ResilientConfig; + secrets: ResilientSecrets; +} + +export interface ResilientActionParams { + subAction: string; + subActionParams: { + savedObjectId: string; + title: string; + description: string; + externalId: string | null; + incidentTypes: number[]; + severityCode: number; + comments: Array<{ commentId: string; comment: string }>; + }; +} + +interface IncidentConfiguration { + mapping: CasesConfigurationMapping[]; +} + +interface ResilientConfig { + apiUrl: string; + orgId: string; + incidentConfiguration?: IncidentConfiguration; + isCaseOwned?: boolean; +} + +interface ResilientSecrets { + apiKeyId: string; + apiKeySecret: string; +} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_incident_types.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_incident_types.tsx new file mode 100644 index 0000000000000..219c6ac77d08d --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_incident_types.tsx @@ -0,0 +1,90 @@ +/* + * 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 { useState, useEffect, useRef } from 'react'; +import { HttpSetup, ToastsApi } from 'kibana/public'; +import { ActionConnector } from '../../../../types'; +import { getIncidentTypes } from './api'; +import * as i18n from './translations'; + +type IncidentTypes = Array<{ id: number; name: string }>; + +interface Props { + http: HttpSetup; + toastNotifications: Pick< + ToastsApi, + 'get$' | 'add' | 'remove' | 'addSuccess' | 'addWarning' | 'addDanger' | 'addError' + >; + actionConnector?: ActionConnector; +} + +export interface UseGetIncidentTypes { + incidentTypes: IncidentTypes; + isLoading: boolean; +} + +export const useGetIncidentTypes = ({ + http, + toastNotifications, + actionConnector, +}: Props): UseGetIncidentTypes => { + const [isLoading, setIsLoading] = useState(true); + const [incidentTypes, setIncidentTypes] = useState([]); + const abortCtrl = useRef(new AbortController()); + + useEffect(() => { + let didCancel = false; + const fetchData = async () => { + if (!actionConnector) { + setIsLoading(false); + return; + } + + abortCtrl.current = new AbortController(); + setIsLoading(true); + + try { + const res = await getIncidentTypes({ + http, + signal: abortCtrl.current.signal, + connectorId: actionConnector.id, + }); + + if (!didCancel) { + setIsLoading(false); + setIncidentTypes(res.data ?? []); + if (res.status && res.status === 'error') { + toastNotifications.addDanger({ + title: i18n.INCIDENT_TYPES_API_ERROR, + text: `${res.serviceMessage ?? res.message}`, + }); + } + } + } catch (error) { + if (!didCancel) { + toastNotifications.addDanger({ + title: i18n.INCIDENT_TYPES_API_ERROR, + text: error.message, + }); + } + } + }; + + abortCtrl.current.abort(); + fetchData(); + + return () => { + didCancel = true; + setIsLoading(false); + abortCtrl.current.abort(); + }; + }, [http, actionConnector, toastNotifications]); + + return { + incidentTypes, + isLoading, + }; +}; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_severity.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_severity.tsx new file mode 100644 index 0000000000000..83689254f000f --- /dev/null +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/resilient/use_get_severity.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 { useState, useEffect, useRef } from 'react'; +import { HttpSetup, ToastsApi } from 'kibana/public'; +import { ActionConnector } from '../../../../types'; +import { getSeverity } from './api'; +import * as i18n from './translations'; + +type Severity = Array<{ id: number; name: string }>; + +interface Props { + http: HttpSetup; + toastNotifications: Pick< + ToastsApi, + 'get$' | 'add' | 'remove' | 'addSuccess' | 'addWarning' | 'addDanger' | 'addError' + >; + actionConnector?: ActionConnector; +} + +export interface UseGetSeverity { + severity: Severity; + isLoading: boolean; +} + +export const useGetSeverity = ({ + http, + toastNotifications, + actionConnector, +}: Props): UseGetSeverity => { + const [isLoading, setIsLoading] = useState(true); + const [severity, setSeverity] = useState([]); + const abortCtrl = useRef(new AbortController()); + + useEffect(() => { + let didCancel = false; + const fetchData = async () => { + if (!actionConnector) { + setIsLoading(false); + return; + } + + abortCtrl.current = new AbortController(); + setIsLoading(true); + + try { + const res = await getSeverity({ + http, + signal: abortCtrl.current.signal, + connectorId: actionConnector.id, + }); + + if (!didCancel) { + setIsLoading(false); + setSeverity(res.data ?? []); + + if (res.status && res.status === 'error') { + toastNotifications.addDanger({ + title: i18n.SEVERITY_API_ERROR, + text: `${res.serviceMessage ?? res.message}`, + }); + } + } + } catch (error) { + if (!didCancel) { + toastNotifications.addDanger({ + title: i18n.SEVERITY_API_ERROR, + text: error.message, + }); + } + } + }; + + abortCtrl.current.abort(); + fetchData(); + + return () => { + didCancel = true; + setIsLoading(false); + abortCtrl.current.abort(); + }; + }, [http, actionConnector, toastNotifications]); + + return { + severity, + isLoading, + }; +}; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_params.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_params.test.tsx index 1fc856b1e1ab2..f4d831d7234e7 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_params.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_params.test.tsx @@ -23,6 +23,7 @@ describe('ServiceNowParamsFields renders', () => { externalId: null, }, }; + const wrapper = mountWithIntl( { const actionParams = { message: 'test message', }; + const wrapper = mountWithIntl( { const actionParams = { body: 'test message', }; + const wrapper = mountWithIntl( { + let resilientSimulatorURL: string = ''; + + // need to wait for kibanaServer to settle ... + before(() => { + resilientSimulatorURL = kibanaServer.resolveUrl( + getExternalServiceSimulatorPath(ExternalServiceSimulator.RESILIENT) + ); + }); + + it('should return 403 when creating a resilient action', async () => { + await supertest + .post('/api/actions/action') + .set('kbn-xsrf', 'foo') + .send({ + name: 'A resilient action', + actionTypeId: '.resilient', + config: { + apiUrl: resilientSimulatorURL, + incidentConfiguration: { ...mockResilient.config.incidentConfiguration }, + isCaseOwned: true, + }, + secrets: mockResilient.secrets, + }) + .expect(403, { + statusCode: 403, + error: 'Forbidden', + message: + 'Action type .resilient is disabled because your basic license does not support it. Please upgrade your license.', + }); + }); + }); +} diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/builtin_action_types/resilient.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/builtin_action_types/resilient.ts index 9cbc2373ef943..d1d19da423e65 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/builtin_action_types/resilient.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/builtin_action_types/resilient.ts @@ -41,9 +41,10 @@ export default function resilientTest({ getService }: FtrProviderContext) { const mockResilient = { config: { - apiUrl: 'www.jiraisinkibanaactions.com', + apiUrl: 'www.resilientisinkibanaactions.com', orgId: '201', - casesConfiguration: { mapping }, + incidentConfiguration: { mapping }, + isCaseOwned: true, }, secrets: { apiKeyId: 'key', @@ -55,6 +56,8 @@ export default function resilientTest({ getService }: FtrProviderContext) { savedObjectId: '123', title: 'a title', description: 'a description', + incidentTypes: [1001], + severityCode: 6, createdAt: '2020-03-13T08:34:53.450Z', createdBy: { fullName: 'Elastic User', username: 'elastic' }, updatedAt: null, @@ -108,7 +111,8 @@ export default function resilientTest({ getService }: FtrProviderContext) { config: { apiUrl: resilientSimulatorURL, orgId: mockResilient.config.orgId, - casesConfiguration: mockResilient.config.casesConfiguration, + incidentConfiguration: mockResilient.config.incidentConfiguration, + isCaseOwned: true, }, }); @@ -124,7 +128,8 @@ export default function resilientTest({ getService }: FtrProviderContext) { config: { apiUrl: resilientSimulatorURL, orgId: mockResilient.config.orgId, - casesConfiguration: mockResilient.config.casesConfiguration, + incidentConfiguration: mockResilient.config.incidentConfiguration, + isCaseOwned: true, }, }); }); @@ -179,7 +184,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { config: { apiUrl: 'http://resilient.mynonexistent.com', orgId: mockResilient.config.orgId, - casesConfiguration: mockResilient.config.casesConfiguration, + incidentConfiguration: mockResilient.config.incidentConfiguration, }, secrets: mockResilient.secrets, }) @@ -204,7 +209,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { config: { apiUrl: resilientSimulatorURL, orgId: mockResilient.config.orgId, - casesConfiguration: mockResilient.config.casesConfiguration, + incidentConfiguration: mockResilient.config.incidentConfiguration, }, }) .expect(400) @@ -218,30 +223,6 @@ export default function resilientTest({ getService }: FtrProviderContext) { }); }); - it('should respond with a 400 Bad Request when creating a ibm resilient action without casesConfiguration', async () => { - await supertest - .post('/api/actions/action') - .set('kbn-xsrf', 'foo') - .send({ - name: 'An IBM Resilient', - actionTypeId: '.resilient', - config: { - apiUrl: resilientSimulatorURL, - orgId: mockResilient.config.orgId, - }, - secrets: mockResilient.secrets, - }) - .expect(400) - .then((resp: any) => { - expect(resp.body).to.eql({ - statusCode: 400, - error: 'Bad Request', - message: - 'error validating action type config: [casesConfiguration.mapping]: expected value of type [array] but got [undefined]', - }); - }); - }); - it('should respond with a 400 Bad Request when creating a ibm resilient action with empty mapping', async () => { await supertest .post('/api/actions/action') @@ -252,7 +233,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { config: { apiUrl: resilientSimulatorURL, orgId: mockResilient.config.orgId, - casesConfiguration: { mapping: [] }, + incidentConfiguration: { mapping: [] }, }, secrets: mockResilient.secrets, }) @@ -262,7 +243,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { statusCode: 400, error: 'Bad Request', message: - 'error validating action type config: [casesConfiguration.mapping]: expected non-empty but got empty', + 'error validating action type config: [incidentConfiguration.mapping]: expected non-empty but got empty', }); }); }); @@ -277,7 +258,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { config: { apiUrl: resilientSimulatorURL, orgId: mockResilient.config.orgId, - casesConfiguration: { + incidentConfiguration: { mapping: [ { source: 'title', @@ -307,7 +288,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { config: { apiUrl: resilientSimulatorURL, orgId: mockResilient.config.orgId, - casesConfiguration: mockResilient.config.casesConfiguration, + incidentConfiguration: mockResilient.config.incidentConfiguration, }, secrets: mockResilient.secrets, }); @@ -353,7 +334,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { status: 'error', retry: false, message: - 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subAction]: expected value to equal [pushToService]', + 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subAction]: expected value to equal [pushToService]\n- [3.subAction]: expected value to equal [incidentTypes]\n- [4.subAction]: expected value to equal [severity]', }); }); }); @@ -371,7 +352,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { status: 'error', retry: false, message: - 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.savedObjectId]: expected value of type [string] but got [undefined]', + 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.savedObjectId]: expected value of type [string] but got [undefined]\n- [3.subAction]: expected value to equal [incidentTypes]\n- [4.subAction]: expected value to equal [severity]', }); }); }); @@ -389,7 +370,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { status: 'error', retry: false, message: - 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.savedObjectId]: expected value of type [string] but got [undefined]', + 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.savedObjectId]: expected value of type [string] but got [undefined]\n- [3.subAction]: expected value to equal [incidentTypes]\n- [4.subAction]: expected value to equal [severity]', }); }); }); @@ -412,31 +393,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { status: 'error', retry: false, message: - 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.title]: expected value of type [string] but got [undefined]', - }); - }); - }); - - it('should handle failing with a simulated success without createdAt', async () => { - await supertest - .post(`/api/actions/action/${simulatedActionId}/_execute`) - .set('kbn-xsrf', 'foo') - .send({ - params: { - ...mockResilient.params, - subActionParams: { - savedObjectId: 'success', - title: 'success', - }, - }, - }) - .then((resp: any) => { - expect(resp.body).to.eql({ - actionId: simulatedActionId, - status: 'error', - retry: false, - message: - 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.createdAt]: expected value of type [string] but got [undefined]', + 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.title]: expected value of type [string] but got [undefined]\n- [3.subAction]: expected value to equal [incidentTypes]\n- [4.subAction]: expected value to equal [severity]', }); }); }); @@ -464,7 +421,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { status: 'error', retry: false, message: - 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.comments]: types that failed validation:\n - [subActionParams.comments.0.0.commentId]: expected value of type [string] but got [undefined]\n - [subActionParams.comments.1]: expected value to equal [null]', + 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.comments]: types that failed validation:\n - [subActionParams.comments.0.0.commentId]: expected value of type [string] but got [undefined]\n - [subActionParams.comments.1]: expected value to equal [null]\n- [3.subAction]: expected value to equal [incidentTypes]\n- [4.subAction]: expected value to equal [severity]', }); }); }); @@ -492,35 +449,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { status: 'error', retry: false, message: - 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.comments]: types that failed validation:\n - [subActionParams.comments.0.0.comment]: expected value of type [string] but got [undefined]\n - [subActionParams.comments.1]: expected value to equal [null]', - }); - }); - }); - - it('should handle failing with a simulated success without comment.createdAt', async () => { - await supertest - .post(`/api/actions/action/${simulatedActionId}/_execute`) - .set('kbn-xsrf', 'foo') - .send({ - params: { - ...mockResilient.params, - subActionParams: { - ...mockResilient.params.subActionParams, - savedObjectId: 'success', - title: 'success', - createdAt: 'success', - createdBy: { username: 'elastic' }, - comments: [{ commentId: 'success', comment: 'success' }], - }, - }, - }) - .then((resp: any) => { - expect(resp.body).to.eql({ - actionId: simulatedActionId, - status: 'error', - retry: false, - message: - 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.comments]: types that failed validation:\n - [subActionParams.comments.0.0.createdAt]: expected value of type [string] but got [undefined]\n - [subActionParams.comments.1]: expected value to equal [null]', + 'error validating action params: types that failed validation:\n- [0.subAction]: expected value to equal [getIncident]\n- [1.subAction]: expected value to equal [handshake]\n- [2.subActionParams.comments]: types that failed validation:\n - [subActionParams.comments.0.0.comment]: expected value of type [string] but got [undefined]\n - [subActionParams.comments.1]: expected value to equal [null]\n- [3.subAction]: expected value to equal [incidentTypes]\n- [4.subAction]: expected value to equal [severity]', }); }); }); @@ -536,7 +465,7 @@ export default function resilientTest({ getService }: FtrProviderContext) { ...mockResilient.params, subActionParams: { ...mockResilient.params.subActionParams, - comments: [], + comments: null, }, }, }) diff --git a/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete.ts b/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete.ts index c6043b7a282d4..53a9d9e790d67 100644 --- a/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete.ts +++ b/x-pack/test/api_integration/apis/ml/data_frame_analytics/delete.ts @@ -120,7 +120,7 @@ export default ({ getService }: FtrProviderContext) => { .expect(404); expect(body.error).to.eql('Not Found'); - expect(body.message).to.eql('Not Found'); + expect(body.message).to.eql('resource_not_found_exception'); }); describe('with deleteDestIndex setting', function () { diff --git a/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/multicluster.json b/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/multicluster.json index b7c3aee5471d7..a000324d121ea 100644 --- a/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/multicluster.json +++ b/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/multicluster.json @@ -102,7 +102,7 @@ }, "alerts": { "alertsMeta": { - "enabled": true + "enabled": false }, "clusterMeta": { "enabled": false, diff --git a/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/clusters.json b/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/clusters.json index f938479578801..7091e584344e7 100644 --- a/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/clusters.json +++ b/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/clusters.json @@ -102,7 +102,7 @@ }, "alerts": { "alertsMeta": { - "enabled": true + "enabled": false }, "clusterMeta": { "enabled": false, @@ -170,7 +170,7 @@ }, "alerts": { "alertsMeta": { - "enabled": true + "enabled": false }, "clusterMeta": { "enabled": false, diff --git a/x-pack/test/case_api_integration/common/lib/utils.ts b/x-pack/test/case_api_integration/common/lib/utils.ts index c23df53c4feef..41f92d022f06c 100644 --- a/x-pack/test/case_api_integration/common/lib/utils.ts +++ b/x-pack/test/case_api_integration/common/lib/utils.ts @@ -99,7 +99,7 @@ export const getResilientConnector = () => ({ config: { apiUrl: 'http://some.non.existent.com', orgId: 'pkey', - casesConfiguration: { + incidentConfiguration: { mapping: [ { source: 'title', @@ -118,6 +118,7 @@ export const getResilientConnector = () => ({ }, ], }, + isCaseOwned: true, }, }); diff --git a/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/actions.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/actions.ts index 2b4bb335dfc5c..68e02933f5650 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/actions.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/actions.ts @@ -28,13 +28,12 @@ export default function (providerContext: FtrProviderContext) { action: { type: 'CONFIG_CHANGE', data: { data: 'action_data' }, - sent_at: '2020-03-18T19:45:02.620Z', }, }) .expect(200); + expect(apiResponse.item.type).to.eql('CONFIG_CHANGE'); expect(apiResponse.item.data).to.eql({ data: 'action_data' }); - expect(apiResponse.item.sent_at).to.be('2020-03-18T19:45:02.620Z'); }); it('should return a 400 when request does not have type information', async () => { diff --git a/x-pack/test/saved_object_api_integration/common/suites/bulk_update.ts b/x-pack/test/saved_object_api_integration/common/suites/bulk_update.ts index 0b5656004492a..2e3c55f029d29 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/bulk_update.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/bulk_update.ts @@ -8,12 +8,7 @@ import expect from '@kbn/expect'; import { SuperTest } from 'supertest'; import { SAVED_OBJECT_TEST_CASES as CASES } from '../lib/saved_object_test_cases'; import { SPACES } from '../lib/spaces'; -import { - createRequest, - expectResponses, - getUrlPrefix, - getTestTitle, -} from '../lib/saved_object_test_utils'; +import { expectResponses, getUrlPrefix, getTestTitle } from '../lib/saved_object_test_utils'; import { ExpectResponseBody, TestCase, TestDefinition, TestSuite } from '../lib/types'; export interface BulkUpdateTestDefinition extends TestDefinition { @@ -21,6 +16,7 @@ export interface BulkUpdateTestDefinition extends TestDefinition { } export type BulkUpdateTestSuite = TestSuite; export interface BulkUpdateTestCase extends TestCase { + namespace?: string; // used to define individual "object namespace" strings, e.g., bulkUpdate across multiple namespaces failure?: 404; // only used for permitted response case } @@ -30,6 +26,12 @@ const NEW_ATTRIBUTE_VAL = `Updated attribute value ${Date.now()}`; const DOES_NOT_EXIST = Object.freeze({ type: 'dashboard', id: 'does-not-exist' }); export const TEST_CASES = Object.freeze({ ...CASES, DOES_NOT_EXIST }); +const createRequest = ({ type, id, namespace }: BulkUpdateTestCase) => ({ + type, + id, + ...(namespace && { namespace }), // individual "object namespace" string +}); + export function bulkUpdateTestSuiteFactory(esArchiver: any, supertest: SuperTest) { const expectForbidden = expectResponses.forbiddenTypes('bulk_update'); const expectResponseBody = ( diff --git a/x-pack/test/saved_object_api_integration/security_and_spaces/apis/bulk_update.ts b/x-pack/test/saved_object_api_integration/security_and_spaces/apis/bulk_update.ts index 90f72e0b34449..1e11d1fc61110 100644 --- a/x-pack/test/saved_object_api_integration/security_and_spaces/apis/bulk_update.ts +++ b/x-pack/test/saved_object_api_integration/security_and_spaces/apis/bulk_update.ts @@ -39,7 +39,18 @@ const createTestCases = (spaceId: string) => { ]; const hiddenType = [{ ...CASES.HIDDEN, ...fail404() }]; const allTypes = normalTypes.concat(hiddenType); - return { normalTypes, hiddenType, allTypes }; + // an "object namespace" string can be specified for individual objects (to bulkUpdate across namespaces) + const withObjectNamespaces = [ + { ...CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, namespace: DEFAULT_SPACE_ID }, + { ...CASES.SINGLE_NAMESPACE_SPACE_1, namespace: SPACE_1_ID }, + { ...CASES.SINGLE_NAMESPACE_SPACE_2, namespace: SPACE_1_ID, ...fail404() }, // intentional 404 test case + { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, namespace: DEFAULT_SPACE_ID }, // SPACE_1_ID would also work + { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, namespace: SPACE_2_ID, ...fail404() }, // intentional 404 test case + { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, namespace: SPACE_2_ID }, + CASES.NAMESPACE_AGNOSTIC, // any namespace would work and would make no difference + { ...CASES.DOES_NOT_EXIST, ...fail404() }, + ]; + return { normalTypes, hiddenType, allTypes, withObjectNamespaces }; }; export default function ({ getService }: FtrProviderContext) { @@ -51,26 +62,42 @@ export default function ({ getService }: FtrProviderContext) { supertest ); const createTests = (spaceId: string) => { - const { normalTypes, hiddenType, allTypes } = createTestCases(spaceId); + const { normalTypes, hiddenType, allTypes, withObjectNamespaces } = createTestCases(spaceId); // use singleRequest to reduce execution time and/or test combined cases + const authorizedCommon = [ + createTestDefinitions(normalTypes, false, { singleRequest: true }), + createTestDefinitions(hiddenType, true), + createTestDefinitions(allTypes, true, { + singleRequest: true, + responseBodyOverride: expectForbidden(['hiddentype']), + }), + ].flat(); return { - unauthorized: createTestDefinitions(allTypes, true), - authorized: [ - createTestDefinitions(normalTypes, false, { singleRequest: true }), - createTestDefinitions(hiddenType, true), - createTestDefinitions(allTypes, true, { - singleRequest: true, - responseBodyOverride: expectForbidden(['hiddentype']), - }), + unauthorized: [ + createTestDefinitions(allTypes, true), + createTestDefinitions(withObjectNamespaces, true, { singleRequest: true }), + ].flat(), + authorizedAtSpace: [ + authorizedCommon, + createTestDefinitions(withObjectNamespaces, true, { singleRequest: true }), + ].flat(), + authorizedAllSpaces: [ + authorizedCommon, + createTestDefinitions(withObjectNamespaces, false, { singleRequest: true }), + ].flat(), + superuser: [ + createTestDefinitions(allTypes, false, { singleRequest: true }), + createTestDefinitions(withObjectNamespaces, false, { singleRequest: true }), ].flat(), - superuser: createTestDefinitions(allTypes, false, { singleRequest: true }), }; }; describe('_bulk_update', () => { getTestScenarios().securityAndSpaces.forEach(({ spaceId, users }) => { const suffix = ` within the ${spaceId} space`; - const { unauthorized, authorized, superuser } = createTests(spaceId); + const { unauthorized, authorizedAtSpace, authorizedAllSpaces, superuser } = createTests( + spaceId + ); const _addTests = (user: TestUser, tests: BulkUpdateTestDefinition[]) => { addTests(`${user.description}${suffix}`, { user, spaceId, tests }); }; @@ -85,8 +112,11 @@ export default function ({ getService }: FtrProviderContext) { ].forEach((user) => { _addTests(user, unauthorized); }); - [users.dualAll, users.allGlobally, users.allAtSpace].forEach((user) => { - _addTests(user, authorized); + [users.allAtSpace].forEach((user) => { + _addTests(user, authorizedAtSpace); + }); + [users.dualAll, users.allGlobally].forEach((user) => { + _addTests(user, authorizedAllSpaces); }); _addTests(users.superuser, superuser); }); diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/bulk_update.ts b/x-pack/test/saved_object_api_integration/security_only/apis/bulk_update.ts index d42eb25b81cf5..39ceb5a70d1b2 100644 --- a/x-pack/test/saved_object_api_integration/security_only/apis/bulk_update.ts +++ b/x-pack/test/saved_object_api_integration/security_only/apis/bulk_update.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { SPACES } from '../../common/lib/spaces'; import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; import { TestUser } from '../../common/lib/types'; import { FtrProviderContext } from '../../common/ftr_provider_context'; @@ -13,6 +14,11 @@ import { BulkUpdateTestDefinition, } from '../../common/suites/bulk_update'; +const { + DEFAULT: { spaceId: DEFAULT_SPACE_ID }, + SPACE_1: { spaceId: SPACE_1_ID }, + SPACE_2: { spaceId: SPACE_2_ID }, +} = SPACES; const { fail404 } = testCaseFailures; const createTestCases = () => { @@ -30,7 +36,19 @@ const createTestCases = () => { ]; const hiddenType = [{ ...CASES.HIDDEN, ...fail404() }]; const allTypes = normalTypes.concat(hiddenType); - return { normalTypes, hiddenType, allTypes }; + // an "object namespace" string can be specified for individual objects (to bulkUpdate across namespaces) + // even if the Spaces plugin is disabled, this should work, as `namespace` is handled by the Core API + const withObjectNamespaces = [ + { ...CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, namespace: DEFAULT_SPACE_ID }, + { ...CASES.SINGLE_NAMESPACE_SPACE_1, namespace: SPACE_1_ID }, + { ...CASES.SINGLE_NAMESPACE_SPACE_2, namespace: SPACE_1_ID, ...fail404() }, // intentional 404 test case + { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, namespace: DEFAULT_SPACE_ID }, // SPACE_1_ID would also work + { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, namespace: SPACE_2_ID, ...fail404() }, // intentional 404 test case + { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, namespace: SPACE_2_ID }, + CASES.NAMESPACE_AGNOSTIC, // any namespace would work and would make no difference + { ...CASES.DOES_NOT_EXIST, ...fail404() }, + ]; + return { normalTypes, hiddenType, allTypes, withObjectNamespaces }; }; export default function ({ getService }: FtrProviderContext) { @@ -42,10 +60,13 @@ export default function ({ getService }: FtrProviderContext) { supertest ); const createTests = () => { - const { normalTypes, hiddenType, allTypes } = createTestCases(); + const { normalTypes, hiddenType, allTypes, withObjectNamespaces } = createTestCases(); // use singleRequest to reduce execution time and/or test combined cases return { - unauthorized: createTestDefinitions(allTypes, true), + unauthorized: [ + createTestDefinitions(allTypes, true), + createTestDefinitions(withObjectNamespaces, true, { singleRequest: true }), + ].flat(), authorized: [ createTestDefinitions(normalTypes, false, { singleRequest: true }), createTestDefinitions(hiddenType, true), @@ -53,8 +74,12 @@ export default function ({ getService }: FtrProviderContext) { singleRequest: true, responseBodyOverride: expectForbidden(['hiddentype']), }), + createTestDefinitions(withObjectNamespaces, false, { singleRequest: true }), + ].flat(), + superuser: [ + createTestDefinitions(allTypes, false, { singleRequest: true }), + createTestDefinitions(withObjectNamespaces, false, { singleRequest: true }), ].flat(), - superuser: createTestDefinitions(allTypes, false, { singleRequest: true }), }; }; diff --git a/x-pack/test/saved_object_api_integration/spaces_only/apis/bulk_update.ts b/x-pack/test/saved_object_api_integration/spaces_only/apis/bulk_update.ts index 93e44e357918a..b51ec303fadf3 100644 --- a/x-pack/test/saved_object_api_integration/spaces_only/apis/bulk_update.ts +++ b/x-pack/test/saved_object_api_integration/spaces_only/apis/bulk_update.ts @@ -16,22 +16,37 @@ const { } = SPACES; const { fail404 } = testCaseFailures; -const createTestCases = (spaceId: string) => [ +const createTestCases = (spaceId: string) => { // for each outcome, if failure !== undefined then we expect to receive // an error; otherwise, we expect to receive a success result - { ...CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, ...fail404(spaceId !== DEFAULT_SPACE_ID) }, - { ...CASES.SINGLE_NAMESPACE_SPACE_1, ...fail404(spaceId !== SPACE_1_ID) }, - { ...CASES.SINGLE_NAMESPACE_SPACE_2, ...fail404(spaceId !== SPACE_2_ID) }, - { - ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, - ...fail404(spaceId !== DEFAULT_SPACE_ID && spaceId !== SPACE_1_ID), - }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, ...fail404(spaceId !== SPACE_1_ID) }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, ...fail404(spaceId !== SPACE_2_ID) }, - CASES.NAMESPACE_AGNOSTIC, - { ...CASES.HIDDEN, ...fail404() }, - { ...CASES.DOES_NOT_EXIST, ...fail404() }, -]; + const normal = [ + { ...CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, ...fail404(spaceId !== DEFAULT_SPACE_ID) }, + { ...CASES.SINGLE_NAMESPACE_SPACE_1, ...fail404(spaceId !== SPACE_1_ID) }, + { ...CASES.SINGLE_NAMESPACE_SPACE_2, ...fail404(spaceId !== SPACE_2_ID) }, + { + ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, + ...fail404(spaceId !== DEFAULT_SPACE_ID && spaceId !== SPACE_1_ID), + }, + { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, ...fail404(spaceId !== SPACE_1_ID) }, + { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, ...fail404(spaceId !== SPACE_2_ID) }, + CASES.NAMESPACE_AGNOSTIC, + { ...CASES.HIDDEN, ...fail404() }, + { ...CASES.DOES_NOT_EXIST, ...fail404() }, + ]; + + // an "object namespace" string can be specified for individual objects (to bulkUpdate across namespaces) + const withObjectNamespaces = [ + { ...CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, namespace: DEFAULT_SPACE_ID }, + { ...CASES.SINGLE_NAMESPACE_SPACE_1, namespace: SPACE_1_ID }, + { ...CASES.SINGLE_NAMESPACE_SPACE_2, namespace: SPACE_1_ID, ...fail404() }, // intentional 404 test case + { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, namespace: DEFAULT_SPACE_ID }, // SPACE_1_ID would also work + { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, namespace: SPACE_2_ID, ...fail404() }, // intentional 404 test case + { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, namespace: SPACE_2_ID }, + CASES.NAMESPACE_AGNOSTIC, // any namespace would work and would make no difference + { ...CASES.DOES_NOT_EXIST, ...fail404() }, + ]; + return { normal, withObjectNamespaces }; +}; export default function ({ getService }: FtrProviderContext) { const supertest = getService('supertest'); @@ -39,8 +54,11 @@ export default function ({ getService }: FtrProviderContext) { const { addTests, createTestDefinitions } = bulkUpdateTestSuiteFactory(esArchiver, supertest); const createTests = (spaceId: string) => { - const testCases = createTestCases(spaceId); - return createTestDefinitions(testCases, false, { singleRequest: true }); + const { normal, withObjectNamespaces } = createTestCases(spaceId); + return [ + createTestDefinitions(normal, false, { singleRequest: true }), + createTestDefinitions(withObjectNamespaces, false, { singleRequest: true }), + ].flat(); }; describe('_bulk_update', () => { diff --git a/yarn.lock b/yarn.lock index 105c5e3cba5ae..66be8ad4490b8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5706,11 +5706,6 @@ ansi-escapes@^1.0.0, ansi-escapes@^1.1.0: resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-1.4.0.tgz#d3a8a83b319aa67793662b13e761c7911422306e" integrity sha1-06ioOzGapneTZisT52HHkRQiMG4= -ansi-escapes@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-2.0.0.tgz#5bae52be424878dd9783e8910e3fc2922e83c81b" - integrity sha1-W65SvkJIeN2Xg+iRDj/Cki6DyBs= - ansi-escapes@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-3.0.0.tgz#ec3e8b4e9f8064fc02c3ac9b65f1c275bda8ef92" @@ -8041,15 +8036,6 @@ camelcase-keys@^2.0.0: camelcase "^2.0.0" map-obj "^1.0.0" -camelcase-keys@^4.0.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-4.2.0.tgz#a2aa5fb1af688758259c32c141426d78923b9b77" - integrity sha1-oqpfsa9oh1glnDLBQUJteJI7m3c= - dependencies: - camelcase "^4.1.0" - map-obj "^2.0.0" - quick-lru "^1.0.0" - camelcase-keys@^6.2.2: version "6.2.2" resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-6.2.2.tgz#5e755d6ba51aa223ec7d3d52f25778210f9dc3c0" @@ -8074,7 +8060,7 @@ camelcase@^3.0.0: resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-3.0.0.tgz#32fc4b9fcdaf845fcdf7e73bb97cac2261f0ab0a" integrity sha1-MvxLn82vhF/N9+c7uXysImHwqwo= -camelcase@^4.0.0, camelcase@^4.1.0: +camelcase@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-4.1.0.tgz#d545635be1e33c542649c69173e5de6acfae34dd" integrity sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0= @@ -8739,15 +8725,6 @@ cliui@^3.0.3, cliui@^3.2.0: strip-ansi "^3.0.1" wrap-ansi "^2.0.0" -cliui@^4.0.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-4.1.0.tgz#348422dbe82d800b3022eef4f6ac10bf2e4d1b49" - integrity sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ== - dependencies: - string-width "^2.1.1" - strip-ansi "^4.0.0" - wrap-ansi "^2.0.0" - cliui@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/cliui/-/cliui-5.0.0.tgz#deefcfdb2e800784aa34f46fa08e06851c7bbbc5" @@ -10347,7 +10324,7 @@ debuglog@^1.0.1: resolved "https://registry.yarnpkg.com/debuglog/-/debuglog-1.0.1.tgz#aa24ffb9ac3df9a2351837cfb2d279360cd78492" integrity sha1-qiT/uaw9+aI1GDfPstJ5NgzXhJI= -decamelize-keys@^1.0.0, decamelize-keys@^1.1.0: +decamelize-keys@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/decamelize-keys/-/decamelize-keys-1.1.0.tgz#d171a87933252807eb3cb61dc1c1445d078df2d9" integrity sha1-0XGoeTMlKAfrPLYdwcFEXQeN8tk= @@ -10548,13 +10525,13 @@ defined@^1.0.0, defined@~1.0.0: resolved "https://registry.yarnpkg.com/defined/-/defined-1.0.0.tgz#c98d9bcef75674188e110969151199e39b1fa693" integrity sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM= -del-cli@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/del-cli/-/del-cli-3.0.0.tgz#327a15d4c18d6b7e5c849a53ef0d17901bc28197" - integrity sha512-J4HDC2mpcN5aopya4VdkyiFXZaqAoo7ua9VpKbciX3DDUSbtJbPMc3ivggJsAAgS6EqonmbenIiMhBGtJPW9FA== +del-cli@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/del-cli/-/del-cli-3.0.1.tgz#2d27ff260204b5104cadeda86f78f180a4ebe89a" + integrity sha512-BLHItGr82rUbHhjMu41d+vw9Md49i81jmZSV00HdTq4t+RTHywmEht/23mNFpUl2YeLYJZJyGz4rdlMAyOxNeg== dependencies: del "^5.1.0" - meow "^5.0.0" + meow "^6.1.1" del@^2.0.2: version "2.2.2" @@ -11860,17 +11837,6 @@ eslint-config-prettier@^6.11.0: dependencies: get-stdin "^6.0.0" -eslint-formatter-pretty@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/eslint-formatter-pretty/-/eslint-formatter-pretty-1.3.0.tgz#985d9e41c1f8475f4a090c5dbd2dfcf2821d607e" - integrity sha512-5DY64Y1rYCm7cfFDHEGUn54bvCnK+wSUVF07N8oXeqUJFSd+gnYOTXbzelQ1HurESluY6gnEQPmXOIkB4Wa+gA== - dependencies: - ansi-escapes "^2.0.0" - chalk "^2.1.0" - log-symbols "^2.0.0" - plur "^2.1.2" - string-width "^2.0.0" - eslint-formatter-pretty@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/eslint-formatter-pretty/-/eslint-formatter-pretty-4.0.0.tgz#dc15f3bf4fb51b7ba5fbedb77f57ba8841140ce2" @@ -12331,19 +12297,6 @@ execa@^0.1.1: object-assign "^4.0.1" strip-eof "^1.0.0" -execa@^0.10.0: - version "0.10.0" - resolved "https://registry.yarnpkg.com/execa/-/execa-0.10.0.tgz#ff456a8f53f90f8eccc71a96d11bdfc7f082cb50" - integrity sha512-7XOMnz8Ynx1gGo/3hyV9loYNPWM94jG3+3T3Y8tsfSstFmETmENCMU/A/zj8Lyaj1lkgEepKepvd6240tBRvlw== - dependencies: - cross-spawn "^6.0.0" - get-stream "^3.0.0" - is-stream "^1.1.0" - npm-run-path "^2.0.0" - p-finally "^1.0.0" - signal-exit "^3.0.0" - strip-eof "^1.0.0" - execa@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/execa/-/execa-0.4.0.tgz#4eb6467a36a095fabb2970ff9d5e3fb7bce6ebc3" @@ -14190,7 +14143,7 @@ globby@^6.1.0: pify "^2.0.0" pinkie-promise "^2.0.0" -globby@^9.1.0, globby@^9.2.0: +globby@^9.2.0: version "9.2.0" resolved "https://registry.yarnpkg.com/globby/-/globby-9.2.0.tgz#fd029a706c703d29bdd170f4b6db3a3f7a7cb63d" integrity sha512-ollPHROa5mcxDEkwg6bPt3QbEf4pDQSNtd6JPL1YvOvAo/7/0VAm9TccUeoTmarjPw4pfUthSCqcyfNB1I3ZSg== @@ -16202,11 +16155,6 @@ iron@5.x.x: cryptiles "4.x.x" hoek "5.x.x" -irregular-plurals@^1.0.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/irregular-plurals/-/irregular-plurals-1.4.0.tgz#2ca9b033651111855412f16be5d77c62a458a766" - integrity sha1-LKmwM2UREYVUEvFr5dd8YqRYp2Y= - irregular-plurals@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/irregular-plurals/-/irregular-plurals-3.2.0.tgz#b19c490a0723798db51b235d7e39add44dab0822" @@ -18753,7 +18701,7 @@ lodash._reinterpolate@^3.0.0: resolved "https://registry.yarnpkg.com/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz#0ccf2d89166af03b3663c796538b75ac6e114d9d" integrity sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0= -lodash.assign@^4.0.3, lodash.assign@^4.0.6, lodash.assign@^4.2.0: +lodash.assign@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/lodash.assign/-/lodash.assign-4.2.0.tgz#0d99f3ccd7a6d261d19bdaeb9245005d285808e7" integrity sha1-DZnzzNem0mHRm9rrkkUAXShYCOc= @@ -19036,7 +18984,7 @@ log-ok@^0.1.1: ansi-green "^0.1.1" success-symbol "^0.1.0" -log-symbols@2.2.0, log-symbols@^2.0.0, log-symbols@^2.1.0, log-symbols@^2.2.0: +log-symbols@2.2.0, log-symbols@^2.1.0, log-symbols@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-2.2.0.tgz#5740e1c5d6f0dfda4ad9323b5332107ef6b4c40a" integrity sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg== @@ -19338,11 +19286,6 @@ map-obj@^1.0.0, map-obj@^1.0.1: resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-1.0.1.tgz#d933ceb9205d82bdcf4886f6742bdc2b4dea146d" integrity sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0= -map-obj@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-2.0.0.tgz#a65cd29087a92598b8791257a523e021222ac1f9" - integrity sha1-plzSkIepJZi4eRJXpSPgISIqwfk= - map-obj@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-4.1.0.tgz#b91221b542734b9f14256c0132c897c5d7256fd5" @@ -19646,20 +19589,22 @@ meow@^3.0.0, meow@^3.3.0, meow@^3.7.0: redent "^1.0.0" trim-newlines "^1.0.0" -meow@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/meow/-/meow-5.0.0.tgz#dfc73d63a9afc714a5e371760eb5c88b91078aa4" - integrity sha512-CbTqYU17ABaLefO8vCU153ZZlprKYWDljcndKKDCFcYQITzWCXZAVk4QMFZPgvzrnUQ3uItnIE/LoUOwrT15Ig== +meow@^6.1.1: + version "6.1.1" + resolved "https://registry.yarnpkg.com/meow/-/meow-6.1.1.tgz#1ad64c4b76b2a24dfb2f635fddcadf320d251467" + integrity sha512-3YffViIt2QWgTy6Pale5QpopX/IvU3LPL03jOTqp6pGj3VjesdO/U8CuHMKpnQr4shCNCM5fd5XFFvIIl6JBHg== dependencies: - camelcase-keys "^4.0.0" - decamelize-keys "^1.0.0" - loud-rejection "^1.0.0" - minimist-options "^3.0.1" - normalize-package-data "^2.3.4" - read-pkg-up "^3.0.0" - redent "^2.0.0" - trim-newlines "^2.0.0" - yargs-parser "^10.0.0" + "@types/minimist" "^1.2.0" + camelcase-keys "^6.2.2" + decamelize-keys "^1.1.0" + hard-rejection "^2.1.0" + minimist-options "^4.0.2" + normalize-package-data "^2.5.0" + read-pkg-up "^7.0.1" + redent "^3.0.0" + trim-newlines "^3.0.0" + type-fest "^0.13.1" + yargs-parser "^18.1.3" meow@^7.0.1: version "7.0.1" @@ -19907,14 +19852,6 @@ minimalistic-crypto-utils@^1.0.0, minimalistic-crypto-utils@^1.0.1: dependencies: brace-expansion "^1.1.7" -minimist-options@^3.0.1: - version "3.0.2" - resolved "https://registry.yarnpkg.com/minimist-options/-/minimist-options-3.0.2.tgz#fba4c8191339e13ecf4d61beb03f070103f3d954" - integrity sha512-FyBrT/d0d4+uiZRbqznPXqw3IpZZG3gl3wKWiX784FycUKVwBt0uLBFkQrtE4tZOrgo78nZp2jnKz3L65T5LdQ== - dependencies: - arrify "^1.0.1" - is-plain-obj "^1.1.0" - minimist-options@^4.0.2: version "4.1.0" resolved "https://registry.yarnpkg.com/minimist-options/-/minimist-options-4.1.0.tgz#c0655713c53a8a2ebd77ffa247d342c40f010619" @@ -20109,15 +20046,15 @@ mocha@^7.1.1: yargs-parser "13.1.2" yargs-unparser "1.6.0" -mochawesome-merge@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/mochawesome-merge/-/mochawesome-merge-2.0.1.tgz#c690433acc78fd769effe4db1a107508351e2dc5" - integrity sha512-QRYok/9y9MJ4zlWGajC/OV6BxjUGyv1AYX3DBOPSbpzk09p2dFBWV1QYSN/dHu7bo/q44ZGmOBHO8ZnAyI+Yug== +mochawesome-merge@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/mochawesome-merge/-/mochawesome-merge-4.1.0.tgz#25a514460c6e106e2c8399daaec2d085b6e89b56" + integrity sha512-cDMzSmYu1dRKcr+ZrjjUEuXSiirU8LTG6R8hrAPlZ7zy1EeL7LLpi+a156obxzqh8quTWmYxKtUbTF2PQt0l7A== dependencies: fs-extra "^7.0.1" - minimatch "^3.0.4" + glob "^7.1.6" uuid "^3.3.2" - yargs "^12.0.5" + yargs "^15.3.1" mochawesome-report-generator@^4.0.0: version "4.0.1" @@ -21556,15 +21493,6 @@ os-locale@^1.4.0: dependencies: lcid "^1.0.0" -os-locale@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-3.0.1.tgz#3b014fbf01d87f60a1e5348d80fe870dc82c4620" - integrity sha512-7g5e7dmXPtzcP4bgsZ8ixDVqA7oWYuEz4lOSujeWyliPai4gfVDiFIcwBg3aGCPnmSGfzOKTK3ccPn0CKv3DBw== - dependencies: - execa "^0.10.0" - lcid "^2.0.0" - mem "^4.0.0" - os-locale@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-3.1.0.tgz#a802a6ee17f24c10483ab9935719cef4ed16bf1a" @@ -22404,13 +22332,6 @@ plugin-error@^1.0.1: arr-union "^3.1.0" extend-shallow "^3.0.2" -plur@^2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/plur/-/plur-2.1.2.tgz#7482452c1a0f508e3e344eaec312c91c29dc655a" - integrity sha1-dIJFLBoPUI4+NE6uwxLJHCncZVo= - dependencies: - irregular-plurals "^1.0.0" - plur@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/plur/-/plur-4.0.0.tgz#729aedb08f452645fe8c58ef115bf16b0a73ef84" @@ -23123,11 +23044,6 @@ queue@6.0.1: dependencies: inherits "~2.0.3" -quick-lru@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/quick-lru/-/quick-lru-1.1.0.tgz#4360b17c61136ad38078397ff11416e186dcfbb8" - integrity sha1-Q2CxfGETatOAeDl/8RQW4Ybc+7g= - quick-lru@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/quick-lru/-/quick-lru-4.0.1.tgz#5b8878f113a58217848c6482026c73e1ba57727f" @@ -24149,14 +24065,6 @@ read-pkg-up@^2.0.0: find-up "^2.0.0" read-pkg "^2.0.0" -read-pkg-up@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-3.0.0.tgz#3ed496685dba0f8fe118d0691dc51f4a1ff96f07" - integrity sha1-PtSWaF26D4/hGNBpHcUfSh/5bwc= - dependencies: - find-up "^2.0.0" - read-pkg "^3.0.0" - read-pkg-up@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-4.0.0.tgz#1b221c6088ba7799601c808f91161c66e58f8978" @@ -24386,14 +24294,6 @@ redent@^1.0.0: indent-string "^2.1.0" strip-indent "^1.0.1" -redent@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/redent/-/redent-2.0.0.tgz#c1b2007b42d57eb1389079b3c8333639d5e1ccaa" - integrity sha1-wbIAe0LVfrE4kHmzyDM2OdXhzKo= - dependencies: - indent-string "^3.0.0" - strip-indent "^2.0.0" - redent@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/redent/-/redent-3.0.0.tgz#e557b7998316bb53c9f1f56fa626352c6963059f" @@ -27023,11 +26923,6 @@ strip-indent@^1.0.1: dependencies: get-stdin "^4.0.1" -strip-indent@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-2.0.0.tgz#5ef8db295d01e6ed6cbf7aab96998d7822527b68" - integrity sha1-XvjbKV0B5u1sv3qrlpmNeCJSe2g= - strip-indent@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-3.0.0.tgz#c32e1cee940b6b3432c771bc2c54bcce73cd3001" @@ -28122,11 +28017,6 @@ trim-newlines@^1.0.0: resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-1.0.0.tgz#5887966bb582a4503a41eb524f7d35011815a613" integrity sha1-WIeWa7WCpFA6QetST301ARgVphM= -trim-newlines@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-2.0.0.tgz#b403d0b91be50c331dfc4b82eeceb22c3de16d20" - integrity sha1-tAPQuRvlDDMd/EuC7s6yLD3hbSA= - trim-newlines@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-3.0.0.tgz#79726304a6a898aa8373427298d54c2ee8b1cb30" @@ -28233,19 +28123,6 @@ tsd@^0.13.1: read-pkg-up "^7.0.0" update-notifier "^4.1.0" -tsd@^0.7.4: - version "0.7.4" - resolved "https://registry.yarnpkg.com/tsd/-/tsd-0.7.4.tgz#d9aba567f1394641821a6800dcee60746c87bd03" - integrity sha512-cqr1s2GHtVkU3L/4BXDaeJOjFEuZ7iOVC+hwmyx4G7Eo26mSXCFNnwFm4EasK/MW2HdY3AQWux+AjYzDYLzZow== - dependencies: - eslint-formatter-pretty "^1.3.0" - globby "^9.1.0" - meow "^5.0.0" - path-exists "^3.0.0" - read-pkg-up "^4.0.0" - typescript "^3.0.1" - update-notifier "^2.5.0" - tslib@^1, tslib@^1.0.0, tslib@^1.10.0, tslib@^1.8.1, tslib@^1.9.0, tslib@^1.9.3: version "1.13.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.13.0.tgz#c881e13cc7015894ed914862d276436fa9a47043" @@ -28412,7 +28289,7 @@ typescript-tuple@^2.2.1: dependencies: typescript-compare "^0.0.2" -typescript@4.0.2, typescript@^3.0.1, typescript@^3.0.3, typescript@^3.2.2, typescript@^3.3.3333, typescript@^3.4.5, typescript@~3.7.2: +typescript@4.0.2, typescript@^3.0.3, typescript@^3.2.2, typescript@^3.3.3333, typescript@^3.4.5, typescript@~3.7.2: version "4.0.2" resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.0.2.tgz#7ea7c88777c723c681e33bf7988be5d008d05ac2" integrity sha512-e4ERvRV2wb+rRZ/IQeb3jm2VxBsirQLpQhdxplZ2MEzGvDkkMmPglecnNDfSUBivMjP93vRbngYYDQqQ/78bcQ== @@ -30240,11 +30117,6 @@ window-size@^0.1.4: resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.4.tgz#f8e1aa1ee5a53ec5bf151ffa09742a6ad7697876" integrity sha1-+OGqHuWlPsW/FR/6CXQqatdpeHY= -window-size@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.2.0.tgz#b4315bb4214a3d7058ebeee892e13fa24d98b075" - integrity sha1-tDFbtCFKPXBY6+7okuE/ok2YsHU= - windows-release@^3.1.0: version "3.2.0" resolved "https://registry.yarnpkg.com/windows-release/-/windows-release-3.2.0.tgz#8122dad5afc303d833422380680a79cdfa91785f" @@ -30614,7 +30486,7 @@ y18n@^3.2.0, y18n@^3.2.1: resolved "https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41" integrity sha1-bRX7qITAhnnA136I53WegR4H+kE= -"y18n@^3.2.1 || ^4.0.0", y18n@^4.0.0: +y18n@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.0.tgz#95ef94f85ecc81d007c264e190a120f0a3c8566b" integrity sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w== @@ -30665,21 +30537,6 @@ yargs-parser@5.0.0-security.0: camelcase "^3.0.0" object.assign "^4.1.0" -yargs-parser@^10.0.0: - version "10.1.0" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-10.1.0.tgz#7202265b89f7e9e9f2e5765e0fe735a905edbaa8" - integrity sha512-VCIyR1wJoEBZUqk5PA+oOBF6ypbwh5aNB3I50guxAL/quggdfs4TtNHQrSazFA3fYZ+tEqfs0zIGlv0c/rgjbQ== - dependencies: - camelcase "^4.1.0" - -yargs-parser@^11.1.1: - version "11.1.1" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-11.1.1.tgz#879a0865973bca9f6bab5cbdf3b1c67ec7d3bcf4" - integrity sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ== - dependencies: - camelcase "^5.0.0" - decamelize "^1.2.0" - yargs-parser@^18.1.1, yargs-parser@^18.1.2, yargs-parser@^18.1.3: version "18.1.3" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-18.1.3.tgz#be68c4975c6b2abf469236b0c870362fab09a7b0" @@ -30688,14 +30545,6 @@ yargs-parser@^18.1.1, yargs-parser@^18.1.2, yargs-parser@^18.1.3: camelcase "^5.0.0" decamelize "^1.2.0" -yargs-parser@^2.4.1: - version "2.4.1" - resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-2.4.1.tgz#85568de3cf150ff49fa51825f03a8c880ddcc5c4" - integrity sha1-hVaN488VD/SfpRgl8DqMiA3cxcQ= - dependencies: - camelcase "^3.0.0" - lodash.assign "^4.0.6" - yargs-unparser@1.6.0: version "1.6.0" resolved "https://registry.yarnpkg.com/yargs-unparser/-/yargs-unparser-1.6.0.tgz#ef25c2c769ff6bd09e4b0f9d7c605fb27846ea9f" @@ -30738,45 +30587,7 @@ yargs@13.3.2, yargs@^13.2.2, yargs@^13.3.0, yargs@^13.3.2: y18n "^4.0.0" yargs-parser "^13.1.2" -yargs@4.8.1: - version "4.8.1" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-4.8.1.tgz#c0c42924ca4aaa6b0e6da1739dfb216439f9ddc0" - integrity sha1-wMQpJMpKqmsObaFznfshZDn53cA= - dependencies: - cliui "^3.2.0" - decamelize "^1.1.1" - get-caller-file "^1.0.1" - lodash.assign "^4.0.3" - os-locale "^1.4.0" - read-pkg-up "^1.0.1" - require-directory "^2.1.1" - require-main-filename "^1.0.1" - set-blocking "^2.0.0" - string-width "^1.0.1" - which-module "^1.0.0" - window-size "^0.2.0" - y18n "^3.2.1" - yargs-parser "^2.4.1" - -yargs@^12.0.5: - version "12.0.5" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-12.0.5.tgz#05f5997b609647b64f66b81e3b4b10a368e7ad13" - integrity sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw== - dependencies: - cliui "^4.0.0" - decamelize "^1.2.0" - find-up "^3.0.0" - get-caller-file "^1.0.1" - os-locale "^3.0.0" - require-directory "^2.1.1" - require-main-filename "^1.0.1" - set-blocking "^2.0.0" - string-width "^2.0.0" - which-module "^2.0.0" - y18n "^3.2.1 || ^4.0.0" - yargs-parser "^11.1.1" - -yargs@^15.0.2, yargs@^15.1.0, yargs@^15.3.1, yargs@^15.4.0: +yargs@^15.0.2, yargs@^15.1.0, yargs@^15.3.1, yargs@^15.4.0, yargs@^15.4.1: version "15.4.1" resolved "https://registry.yarnpkg.com/yargs/-/yargs-15.4.1.tgz#0d87a16de01aee9d8bec2bfbf74f67851730f4f8" integrity sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==